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?
I tried this simple thing and it seems to be working.
It works for me.
If this does not work try to run your Java application with sudo if on linux and as administrator when on windows. Just to make sure Java has rights to change the file properties.
if file.delete() is sending false then in most of the cases your Bufferedreader handle will not be closed. Just close and it seems to work for me normally.
The problem could be that the file is still seen as opened and locked by a program; or maybe it is a component from your program that it had been opened in, so you have to ensure you use the
dispose()
method to solve that problem. i.e.JFrame frame; .... frame.dispose();
I had the same problem on Windows. I used to read the file in scala line by line with
Now I read it as a whole with
which closes the file properly after reading and now
works.