Reputation: 444
I am trying to write simple objects (SimpleType
) into files, so that the files can be loaded later and the objects recreated.
I am currently working in the NetBeans IDE (JDK8) on a Windows 7 machine. I don't think that should make a difference, though.
This is the type I would like to write into the file:
public class SimpleType implements Serializable {
boolean[] a;
boolean[] b;
}
This is the code I'm trying to get to run:
public class Test {
public static void main(String[] args)
throws IOException, ClassNotFoundException {
String fileName = "test.txt";
SimpleType foo = new SimpleType;
try (ObjectOutputStream out = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(fileName)))) {
out.writeObject(foo);
out.close();
}
}
}
The code compiles and runs, but always throws a FileNotFoundException
:
Exception in thread "main" java.io.FileNotFoundException: test.txt (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at Test.main(Test.java:33)
public FileOutputStream(String name) throws FileNotFoundException
[...]
Parameters:
name
- the system-dependent filename
Throws:
FileNotFoundException
- if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reasonSecurityException
- if a security manager exists and its checkWrite method denies write access to the file.
I am sure that I have read/write permissions in the directory; there is no existing file with the name test.txt so it cannot be locked by another program.
Changing fileName
to an absolute path I am sure I can write into doesn't make any difference.
Upvotes: 3
Views: 7352
Reputation: 2477
It is reproducible if file is in read-only mode. Can you try like this.
public static void main(String[] args) {
String fileName = "sampleObjectFile.txt";
SampleObject sampleObject = new SampleObject();
File file = new File(fileName);
file.setWritable(true); //make it writable.
try(ObjectOutputStream outputStream = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)))){
outputStream.writeObject(sampleObject);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are writing the file on OS disk you need admin privileges. so avoid writing on OS disk.
Upvotes: 3
Reputation: 647
Normally this is because you are trying to write on a location not allowed by your FileSystem (for example in Windows7 you cannot write a new file in c:). Try to investigate where the program is trying to write using procmon from Microsoft's SysInternals. Add a new filter (path contains test.txt) and see what happens.
Upvotes: 1