Java - 递归删除父路径的文件和文件夹

Sid*_*eva 1 java file

我正在创建一个java程序,它接受父路径并删除给定路径中的所有文件和文件夹.我能够删除父文件夹中另一个文件夹中的文件和文件夹的文件,但无法删除第3级的文件夹.

这是我的代码:

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

小智 6

您应该考虑使用Apache Commons-IO.它有一个FileUtils类,其方法是deleteDirectory,它将以递归方式删除.

注意: Apache Commons-IO(与2.5版一样)仅为遗留java.ioAPI(File和朋友)提供实用程序,而不是为Java 7+ java.nioAPI(Path和朋友)提供实用程序.


Pri*_*rim 6

您可以在Stream API中使用""new""Java File API:

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

请注意,对sorted()方法的调用是在目录之前删除所有文件.

关于一个声明,没有任何第三方库;)