2

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?

user207421
  • 305,947
  • 44
  • 307
  • 483
John Black
  • 305
  • 2
  • 8
  • 19

1 Answers1

3

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException at man.main(man.java:10) – John Black Aug 27 '13 at 23:32
  • 2
    @JohnBlack `FileNotFoundException` is a checked exception. You need to either wrap it in a `try-catch` block or make your method rethrow it by declaring that the method `throws FileNotFoundException`, like I've shown in my answer (I used `Exception` because it's a parent class). – Sotirios Delimanolis Aug 27 '13 at 23:35
  • Ok I have put throws IOException in the main class and now it is working, weird. – John Black Aug 27 '13 at 23:37
  • 1
    @JohnBlack When you complain about compilation errors in code provided, make sure you have transcribed it correctly. You didn't. – user207421 Aug 28 '13 at 01:35