17

I have been using a specific piece of code to delete files from a folder but it is proving very problematic because maybe I forgot to close an InputStream or two. The code I have is so big that I am not be able to see all the Inputstreams that I have not closed. Is there a way of deleting files whether there is an open InputStream or not?

This is the piece of the code that I have been using;

File fin = new File("C:/ABC Statements final/");
    File[] finlist = fin.listFiles();       
    for (int n = 0; n < finlist.length; n++) {
        if (finlist[n].isFile()) {
        System.gc();
        Thread.sleep(2000);
            finlist[n].delete();
        }
    }        

I have edited the code. This version works.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Stanley Mungai
  • 4,044
  • 30
  • 100
  • 168

7 Answers7

27

There is no InputStream instances in the provided chunk of code.

To not write lots of untested IO code, please take a look at the apache.commons.io project. Especially at the FileDeleteStrategy class, for file deletion operations.

Your code might look like that:

File fin = new File("C:/ABC Statements final/");

for (File file : fin.listFiles()) {
    FileDeleteStrategy.FORCE.delete(file);
}   
Dmytro Chyzhykov
  • 1,814
  • 1
  • 20
  • 17
  • 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 – Stanley Mungai Jul 12 '12 at 08:21
  • if you replace the `delete` method with `deleteQuietly` one. In this case **if a file could not be deleted, no exception will be thrown**. – Dmytro Chyzhykov Jul 12 '12 at 09:56
  • 8
    It is not the Exceptions I want to get rid of, I need the files deleted. – Stanley Mungai Jul 12 '12 at 10:57
  • 1
    please read this thread - http://stackoverflow.com/questions/991489/i-cant-delete-a-file-in-java – Dmytro Chyzhykov Jul 12 '12 at 11:00
  • Actually, That's Windows, baby! – Dmytro Chyzhykov Jul 12 '12 at 11:01
  • 4
    Actually From the Link you Shared Above, I found the Answer to My Problem. I have added the bit `System.gc()` and the bit `Thread.sleep` and the files are getting deleted. Thank you Man. – Stanley Mungai Jul 12 '12 at 11:47
5

You can use:

FileUtils.deleteDirectory(File directory)

from Apache Commons

Pawel
  • 798
  • 8
  • 28
  • 4
    Probably better to use `cleanDirectory()` since it says it doesn't delete the directory. However, I'm not 100% sure what "clean" means. I *assume* it means it deletes the directory contents, but the documentation is *awful*, so I can't be certain. – Timmmm Nov 21 '12 at 18:25
3

With Apache Commons IO:

File dir = ...
FileUtils.deleteQuietly(dir);
dir.mkdirs();

No need to check for exceptions this way.

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
3

Use:

   import org.apache.commons.io.FileUtils;
   FileUtils.cleanDirectory(fin);

Docs:

 /**
     * Clean a directory without deleting it.
     *
     * @param directory directory to clean
     * @throws IOException in case cleaning is unsuccessful
     */

In order to use it you need a dependency:

Maven:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Gradle:

compile 'commons-io:commons-io:2.6'
Xelian
  • 16,680
  • 25
  • 99
  • 152
  • Sometimes libraries are life saver. Java is very good language but unfortunately it is making something difficult. – kodmanyagha Dec 11 '21 at 23:01
1
public void removeDir()
{
try
{
    File dir = new File((System.getProperty("user.dir")+"/ReportFolderToMail"+timeStamp));
    if (dir.isDirectory())
    {
        File[] files = dir.listFiles();
        if (files != null && files.length > 0)
        {
            for (File aFile : files) 
            {
                System.gc();
                Thread.sleep(2000);
                 FileDeleteStrategy.FORCE.delete(aFile);
                System.out.println("delet file" +aFile);
            }
        }
        dir.delete();
        System.out.println("delet" +dir);
    } 
    else 
    {
        dir.delete();
    }
}
catch(Exception e)
{
    e.printStackTrace();
}
0
public boolean removeDir()
{
try
{
   //destFile = new File((System.getProperty("user.dir")+"/FileName"))
   // checks if the directory has any file
    File dir = destFile; 
    if (dir.isDirectory())
    {
        File[] files = dir.listFiles();
        if (files != null && files.length > 0)
        {
            for (File aFile : files) 
            {
                System.gc();
                Thread.sleep(2000);
                FileDeleteStrategy.FORCE.delete(aFile);
                System.out.println("delet file" +aFile);
            }
        }
        dir.delete();
        System.out.println("delet" +dir);
    } 
    else 
    {
        dir.delete();
    }
}
catch(Exception e)
{
    logger.log(LogStatus.FATAL, "Exception Occured While Deleting Folder : " +e);
}
return true;
}
0

I simply did this and it worked awesomely:

            System.gc();
            //then
            Files.delete(chosenFile.toPath());
            FileDeleteStrategy.FORCE.delete(chosenFile);