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?
Restart your IDE and run your code again this is only trick work for me after one hour long struggle.
Here is my code:
Output:
Delete
Hopefully this will help. I came across similar problem where i couldn't delete my file after my java code made a copy of the content to the other folder. After extensive googling, i explicitly declared every single file operation related variables and called the close() method of each file operation object, and set them to NULL. Then, there is a function called System.gc(), which will clear up the file i/o mapping (i'm not sure, i just tell what is given on the web sites).
Here is my example code:
the answer is when you load the file, you need apply the "close" method, in any line of code, works to me
If you are working in Eclipse IDE, that could mean that you haven't close the file in the previous launch of the application. When I had the same error message at trying to delete a file, that was the reason. It seems, Eclipse IDE doesn't close all files after termination of an application.
You have to close all of the streams or use try-with-resource block
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
andFileOutputStream
to be incompatible.