Hi Guys I am trying to delete Files from a folder and I have tried these two methods which are Not deleting the files;
First Methos is :
The second Method is :
Both Methods Give this Exception :
Exception in thread "main" java.io.IOException: Unable to delete file: C:\ABC Statements final\Statement0.RPT at org.apache.commons.io.FileUtils.forceDelete(FileUtils.java:1390) at org.apache.commons.io.FileDeleteStrategy$ForceFileDeleteStrategy.doDelete(FileDeleteStrategy.java:151) at org.apache.commons.io.FileDeleteStrategy.delete(FileDeleteStrategy.java:94) at abcbankestatement.ABCBankEStatement.main(ABCBankEStatement.java:502) Java Result: 1
Is there a Better way to force the deletion of these files??
Give a beggar a fish; feed him for a day. Teach him how to fish; Feed him for a lifetime.
The most common reason for this to happen is - the file is locked by another process/thread. It can be part of your code(in which case, you need to check whether any part of your code is keeping the file open etc.), or you are providing that file to some other application, which is not properly closing it etc.
Please make sure that file is not locked by any other thread (apart from the thread which attempts to delete it).
1. "Why is there no escape character after "C:/" in ?it should be "C://"
2. this syntax i could not understand , is "Statements" and "final" name of files?
3. I don't think we can put any file names like this.
4. Just remove these name and put escape sequence after C
also you can use apache commons-io, which is an excellent library for performing everything related to IO. it has got functions with which you can delete files forcibly. it is really good. give it a try.
Joined: Nov 10, 2008
that name is folder name. we don't need to put escape sequence also. it works the way written.need to learn more
what Anayonkar said could be possible reason.
Anayonkar was actually Partly right. Although I had closed all the InputStream that were reading from the Directory. the deletion was happening so soon that the bufferedReaders and the InputStream had no enough time to close. So I added this part of the code and the Deletion Now happens!!!
the edited code:
And the deletion happened. Thank you Guys for helping.
Stanley Mungai wrote:the deletion was happening so soon that the bufferedReaders and the InputStream had no enough time to close
That's very strange. Are you manually flushing and closing all streams before attempting to delete the file?
And as Jesper de Jong said, its very bad idea to have code where behavior depends on time taken by GC. What if GC chooses not to clean-up resources (because, memory usage is, say only 5%, or for some other reason)?