Question

I am trying to access a file to read it and write on it using this code:

RandomAccessFile file1 = new RandomAccessFile("C:\\lol.txt", "rw");

It returns me an error "File not Found (IOException)".

The file exists and it is in that exact folder. What am I missing?

Était-ce utile?

La solution

Unless your run your Java application as an administrator, you won't have write access to C:.

The following code

public static void main(String[] args) throws Exception {   
    RandomAccessFile file1 = new RandomAccessFile("C:\\lol.txt", "rw");
}

will give you

Exception in thread "main" java.io.FileNotFoundException: C:\lol.txt (Access is denied)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(Unknown Source)
at java.io.RandomAccessFile.<init>(Unknown Source)
at Test.Main.main(Main.java:79)

The javadoc for RandomAccessFile constructor states this:

FileNotFoundException - if the mode is "r" but the given string does not denote an existing regular file, or if the mode begins with "rw" but the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file

Just move your file to another location, like C:\Users\You.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top