Reputation: 11
Unable to delete files even after closing the corresponding readers and writers. Permissions are present on the files file.delete() returns false my code
main(){
try{
File file=new File(path);// Path where the file is present
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
FileWriter writer = new FileWriter(pathOther);
BufferedWriter wr = new BufferedWriter(writer);
// Readers and writers for i/o operations
while((String str=br.readLine())!=null){
wr.write(str); // Copying to another file
}
}catch(Exception e){}
finally{
reader.close(); //close reader
writer.close(); //close writer
file.delete(); //This returns false
}
Upvotes: 0
Views: 732
Reputation: 11621
First, you should close the BufferedReader
instead of the FileReader
(the BufferedReader
will in turn call close()
on the FileReader
):
So instead of:
reader.close(); //close reader
do:
br.close();
(and leave out the complete redundant comment).
Also, since File.delete()
simply returns a Boolean and doesn't tell you why it failed, you can get more information by calling Files.delete
instead:
try {
Files.delete(file.toPath());
} catch (IOException e) {
// e now contains information about why it can't delete.
}
Upvotes: 0
Reputation: 521239
My guess as to what is going on is that you close the FileInputStream
but leave the BufferedReader
open, which leaves something holding on to the file handle. Then, when you try to delete the file, it returns false
because something else has a handle on it.
Try the following code:
File file = new File(path);
try {
br = new BufferedReader(new FileReader(file));
// use the reader ...
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// now close the file
file.delete();
Update:
While testing the above code I noticed something else which could also cause the observations you were seeing. If the file at path
does not exist, then logically calling file.delete
will also fail for this reason. So you should make sure that the file actually exists before trying to delete it. You can call file.exists()
to check for this.
Upvotes: 2