0

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();
}
  • 2
    What is the error message? What operating system are you using? – rghome Dec 21 '21 at 16:01
  • @rghome The program is a GUI that I've made into an .exe using Launch4j, so I cannot see the error message, at least not that I know. I haven't been able to replicate this problem while running it in a way that lets me see the error message. However I can tell you that the file is created but nothing is written to it, leading me to believe that the file cannot be opened for some reason. I'm running Windows 10. – gustavaman Dec 21 '21 at 16:20
  • Please improve your question by adding more information and also error message – Saman Salehi Dec 29 '21 at 08:02

1 Answers1

0

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.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • The problem is not easy to replicate, and for that reason it's difficult to know if sleep() solves the problem, or if it isn't occuring for some other reason. I do, however, think that you are correct in saying that this is a Windows problem. I will rewrite my program so that it doesn't create a second FOS, but instead uses the first. Will this eliminate the problem, or do you think that it could still occur? Thanks for your answer! – gustavaman Dec 21 '21 at 16:31