gustavaman
gustavaman

Reputation: 1

Issues with multiple FileOutputStreams to the same file in Java

I'm trying to write to a file using FileOutputStream. When the user selects what file to write to, the program tries to create a FileOutputStream using that file, to check if it works. If it does not, the user has to select a different file. If it does work, the FileOutputStream is closed.

After a file, for which a FOS can be opened, has been selected the program tries again to create another FOS, but this sometimes fails.

I know that you cannot write to a file when it is open on your computer. Could it be that the first FOS has not been "fully closed" and therefore the file is still considered open, so that the second FOS can not write to it?

In the following code, what happens is that the first creation and closing of the FOS does not throw an exception, while the second one somehow does. How can this be?

(I know the problem can be solved by simply using the first FOS and not creating a second, but I am interested in understanding why this particular code behaves the way it does.)

try {
    FileOutputStream out1 = new FileOutputStream(file);
    out1.close();
} catch (Exception e) {
    e.printStackTrace();
}
try {
    FileOutputStream out2 = new FileOutputStream(file);
} catch (Exception e) {
    e.printStackTrace();
}

Upvotes: 0

Views: 487

Answers (1)

Stephen C
Stephen C

Reputation: 718836

Based on the symptoms, I surmise that you are using Windows, and the error you are getting in the second open is "file is in use".

Apparently under some circumstances, Windows does not immediately close a file when the application (in this case the JVM) closes the FileHandle:

This is not Java's doing, and I am not aware of a workaround (in Java) apart from waiting a bit and retrying.

(You could see what happens if you add a Thread.sleep(1000); before the 2nd attempt to create a FileOutputStream.)

Upvotes: 1

Related Questions