I'm trying to delete a file, after writing something in it, with FileOutputStream
. This is the code I use for writing:
private void writeContent(File file, String fileContent) { FileOutputStream to; try { to = new FileOutputStream(file); to.write(fileContent.getBytes()); to.flush(); to.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
As it is seen, I flush and close the stream, but when I try to delete, file.delete()
returns false.
I checked before deletion to see if the file exists, and: file.exists()
, file.canRead()
, file.canWrite()
, file.canExecute()
all return true. Just after calling these methods I try file.delete()
and returns false.
Is there anything I've done wrong?
Another bug in Java. I seldom find them, only my second in my 10 year career. This is my solution, as others have mentioned. I have nether used System.gc()
. But here, in my case, it is absolutely crucial. Weird? YES!
finally { try { in.close(); in = null; out.flush(); out.close(); out = null; System.gc(); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } }
It was pretty odd the trick that worked. The thing is when I have previously read the content of the file, I used BufferedReader
. After reading, I closed the buffer.
Meanwhile I switched and now I'm reading the content using FileInputStream
. Also after finishing reading I close the stream. And now it's working.
The problem is I don't have the explanation for this.
I don't know BufferedReader
and FileOutputStream
to be incompatible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With