0

I have this code, which must remove files from the directory and the directory itself:

private static void removeTempFiles(File dir){
        if(!dir.exists())
            return;
        if(dir.isDirectory()){
            for(File f : dir.listFiles())
                removeTempFiles(f);
            dir.delete();
        }
        else {
            dir.delete();
        }
    }

but executing this code don't remove all the files. From time to time it removes all files with the folder or removes only a few files

UPD: here is my creating file code:

 File tempFolder = new File(tempPath);
    tempFolder.mkdir();
    tempFolder.mkdirs();    
    FileOutputStream fileOut = new            FileOutputStream(tempPath+"/"+fileName);    
        OutputStreamWriter osw = new OutputStreamWriter(fileOut, "windows-1251");
            try{
                osw.write(file64);
            } catch (IOException e){
                e.printStackTrace();
            }finally {
osw.close();
                fileOut.close();
            }
Nikitin Mikhail
  • 2,983
  • 9
  • 42
  • 67

1 Answers1

1

On Windows, it's normal that file deletion does not always succeed, because files can be locked by various services running on the system (antivirus, search indexing etc.). You need to add a retry loop around every file deletion call.

yole
  • 92,896
  • 20
  • 260
  • 197
  • u mean do it until file.delete is true? – Nikitin Mikhail Mar 04 '15 at 10:08
  • Usually you don't want to make an infinite number of retries. 10 attempts is usually OK. – yole Mar 04 '15 at 10:09
  • @I've just create a loop until file.delete is true and it is still running. much more then 10 attempts – Nikitin Mikhail Mar 04 '15 at 10:25
  • Then the file is actually locked by some other process. You can use [Process Explorer](https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to check which process has opened the file. – yole Mar 04 '15 at 10:26
  • there are no processes using this file when my app is not running. and when the app is running, I mean when the deleting loop is executing some 'non-existent process' is using it, which, i guess is the app itself – Nikitin Mikhail Mar 04 '15 at 10:44
  • and what is interesting that only one of two created at one time files can't be removed. – Nikitin Mikhail Mar 04 '15 at 10:45