MaxAxeHax
MaxAxeHax

Reputation: 444

FileNotFoundException (Access is denied) when trying to write to a new file

My goal

I am trying to write simple objects (SimpleType) into files, so that the files can be loaded later and the objects recreated.

My setting

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();
        }
    }
}

My problem

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)

My attempts to fix it

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 reason SecurityException - if a security manager exists and its checkWrite method denies write access to the file.

Upvotes: 3

Views: 7352

Answers (2)

Lovababu Padala
Lovababu Padala

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

alphamikevictor
alphamikevictor

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

Related Questions