Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

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?

like image 865
Jenny Smith Avatar asked Jun 13 '09 20:06

Jenny Smith


2 Answers

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();     } } 
like image 119
Da Martin Avatar answered Sep 17 '22 13:09

Da Martin


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.

like image 34
Jenny Smith Avatar answered Sep 17 '22 13:09

Jenny Smith