简体   繁体   中英

Java - Deleting files and folder of parent path recursively

I'm creating a java program which takes parent path and deletes all the files and folders in the given path. I'm able to delete files and folder's files inside another folder in the parent folder but not able to delete folders at 3rd level.

Here's my code:

package com.sid.trial;

import java.util.List;
import java.io.File;
import java.util.ArrayList;

public class DeleteFilesOfDirectoryWithFilters {

    public static void main(String[] args) {
        String parentPath = "D:\\tester";
        List<String> folderPaths =  deleteFiles(parentPath);
        deleteFolders(folderPaths);
    }

    public static void deleteFolders(List<String> folderPaths) {

        for(String path : folderPaths){
            File folder = new File(path);
            if(folder.delete())
                System.out.println("Folder "+folder.getName()+" Successfully Deleted.");
        }
    }

    public static List<String> deleteFiles(String path){
        File folder = new File(path);
        File[] files = folder.listFiles();
        List<String> folderPaths = new ArrayList<String>();
        String folderPath = path;
        if(files.length == 0){
            System.out.println("Directory is Empty or No FIles Available to Delete.");
        }
        for (File file : files) {
            if (file.isFile() && file.exists()) {
                file.delete();
                System.out.println("File "+file.getName()+" Successfully Deleted.");
            } else {
                if(file.isDirectory()){
                    folderPath = file.getAbsolutePath();
                    char lastCharacter = path.charAt(path.length()-1);
                    if(!(lastCharacter == '/' || lastCharacter == '\\')){

                        folderPath = folderPath.concat("\\");
                    }
                    /*folderPath = folderPath.concat(file.getName());*/
                    System.out.println(folderPath);
                    folderPaths.add(folderPath);
                }
            }
        }
        for(String directoryPath : folderPaths){
            List<String> processedFiles = new ArrayList<String>();
            processedFiles = deleteFiles(directoryPath);
            folderPaths.addAll(processedFiles);
        }
        return folderPaths;
    }

}

You should consider using Apache Commons-IO . It has a FileUtils class with a method deleteDirectory that will recursively delete.

Note: Apache Commons-IO (as for version 2.5) provides utilities only for legacy java.io API ( File and friends), not for Java 7+ java.nio API ( Path and friends).

You can use the ""new"" Java File API with Stream API:

 Path dirPath = Paths.get( "./yourDirectory" );
 Files.walk( dirPath )
      .map( Path::toFile )
      .sorted( Comparator.comparing( File::isDirectory ) ) 
      .forEach( File::delete );

Note that the call to sorted() method is here to delete all files before directories.

About one statement, and without any third party library ;)

You can recursively traverse through the folder and delete each file one by one. After deleting all the files in one folder, delete the folder. Something similar to following code should work:

public void delete(File path){
    File[] l = path.listFiles();
    for (File f : l){
        if (f.isDirectory())
            delete(f);
        else
            f.delete();
    }
    path.delete(); 
}

You can do the following, your recursion is longer than needed.

public static void deleteFiles (File file){    
    if(file.isDirectory()){
        File[] files = file.listFiles();   //All files and sub folders
        for(int x=0; files != null && x<files.length; x++)
            deleteFiles(files[x]);          
    }
    else
        file.delete();      
}

Explanation:

  1. When invoke deleteFiles() on a file , the else statement gets triggered, the single file will be deleted with no recursion.

  2. When invoke deleteFiles() on a folder , the if-statement gets triggered.

    • Get all the entries (files of folders residing in the folder) as an array
    • If there exist sub-entries, for each entry, recursively delete the sub-entry (the same process (1 and 2) repeats).

Be careful when implementing deletion of file and folders. You may want to print out all the files and folders name first instead of deleting them. Once confirmed it is working correctly, then use file.delete() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM