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?

7
  • 3
    Do you have permission to write to the file? Commented Aug 27, 2013 at 22:51
  • Are you sure you have the capitalization right? Commented Aug 27, 2013 at 22:52
  • Yes I have permission and the capitalization is correct. Commented Aug 27, 2013 at 22:55
  • Since it's read-write mode the file would be created if it didn't exist, but "File not Found" is also an error that computers tend to throw up if there's a permissions issue, so it really sounds like that's what it is. Commented Aug 27, 2013 at 22:57
  • 1
    You're not typically supposed to have permission to write to C:\ . This is a permission error. Put it in your My Documents folder. Commented Aug 27, 2013 at 22:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException at man.main(man.java:10)
@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).
Ok I have put throws IOException in the main class and now it is working, weird.
@JohnBlack When you complain about compilation errors in code provided, make sure you have transcribed it correctly. You didn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.