Dannon
Dannon

Reputation: 2216

FileNotFoundException - The Process cannot access the file

I have a network drive at school, I have the ability to read and write to it normally, but when I use java to take an existing text file and try and write to it, I get this exception:

java.io.FileNotFoundException: p:\CompSci_CheckIn_Name.txt (The process cannot access the file because it is being used by another process)

I can read it just fine and all but when I try and write to it, it throws me an exception. I can write to my desktop and read and everything from my desktop but when I try my network drive, it gives up. How could I get around this problem?

Reading

file = new File(directories[i], "CompSci_CheckIn_Name.txt");
readName = new BufferedReader(new FileReader(file));
userName = readName.readLine();
passed = true;

Writing

write = new PrintWriter(file);
write.println(newUser);
write.flush();
userName = newUser;
write.close();

I have already tried a BufferedWriter with no luck, same result.

Upvotes: 1

Views: 10591

Answers (1)

Insuk Cho
Insuk Cho

Reputation: 66

You should close() BufferedReader and FileReader after using them.

Use a try/finally block and close your Readers in the finally block.

FileReader fr = null;
BufferdReader br = null;

try {
    fr = new FileRader(file);
    br = new BufferedReader(fr);

    // do something..

} finally {
    if (br != null) br.close();
    if (fr != null) fr.close();
}

Upvotes: 5

Related Questions