I am aware that this question is a raging duplicate of this question. However, I have now read that entire page twice, and some sections 3 times, and for th
You can only delete the file if there is no file handler left opened. Since you open the file hanlder using FileWriter
, you will need to close it before you can delete it. In other word, f.delete
must be executed after fw.close
Try the code below. I made the changes to prevent all possible bug you may found, e.g if fw is null.
File f = null;
FileWriter fw = null;
try {
f = new File("myFile.txt");
fw = new FileWriter(f);
fw.write("This is a sentence that should appear in the file.");
fw.flush(); // flush is not needed if this is all your code does. you data
// is automatically flushed when you close fw
} catch (Exception exc) {
System.err.println(exc.getMessage());
} finally {// finally block is always executed.
// fw may be null if an exception is raised in the construction
if (fw != null) {
fw.close();
}
// checking if f is null is unneccessary. it is never be null.
if (f.delete()) {
System.out.println("File was successfully deleted.");
} else {
System.err.println("File was not deleted.");
}
}