【问题标题】:Java - Deleting files and folder of parent path recursivelyJava - 递归删除父路径的文件和文件夹
【发布时间】:2016-03-02 10:59:16
【问题描述】:

我正在创建一个 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;
    }

}

【问题讨论】:

  • 这是一个练习吗?否则你可以看看 commons-io - FileUtils.cleanDirectory: commons.apache.org/proper/commons-io/apidocs/src-html/org/…
  • @Siddharth 看看下面我的解决方案。
  • 请不要要求读者为您做所有事情 - Stack Overflow 不是免费的编码服务。关键是人们愿意帮助您实现目标,因此愿意接受人们的想法和建议,并将其修改为您的用例。

标签: java file


【解决方案1】:

您可以将“新”Java File API 与 Stream API 一起使用:

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

注意这里调用sorted()方法是为了删除目录之前的所有文件。

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

【讨论】:

  • 这段代码真的很新,谢谢分享:)。你能解释一下吗?现在让我看看如何打印所有文件和文件夹名称,就像我在代码中使用 File API 和 Stream API 一样。?
  • Files.walk() 将所有现有路径的 Stream 返回到目录中。 map() 将 Path 对象转换为 File 对象,forEach() 对每个对象应用一些东西。要在处理过程中打印文件路径,您可以将 lambda 扩展为 forEach() 并添加一条语句:forEach( file -&gt; { System.out.println( file ); file.delete(); } );
【解决方案2】:

您应该考虑使用Apache Commons-IO。它有一个 FileUtils 类和一个方法 deleteDirectory 将递归删除。

注意: Apache Commons-IO(对于 2.5 版)仅为旧版 java.io API(File 和朋友)提供实用程序,不适用于 Java 7+ java.nio API(@ 987654325@和朋友们)。

【讨论】:

  • 这也会删除父文件夹。问题是如何保留父文件夹但删除其中的所有文件。
【解决方案3】:

可以递归遍历文件夹,将每个文件一一删除。删除一个文件夹中的所有文件后,删除该文件夹。类似于以下代码的东西应该可以工作:

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

【讨论】:

  • 在 windows 10 机器上给出 java.lang.StackOverFlowError。上面的代码有什么线索/改进吗?
  • 此代码在 Java 1.8 和 Windows 8.1 中运行良好。谢谢@santosh-patil
【解决方案4】:

您可以执行以下操作,您的递归比需要的要长。

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

说明:

  1. 当在文件上调用deleteFiles()时,else语句被触发,单个文件将被删除而不递归。

  2. 当在 文件夹 上调用 deleteFiles() 时,会触发 if 语句。

    • 以数组形式获取所有条目(文件夹中的文件夹文件)
    • 如果存在子条目,对于每个条目,递归删除子条目(相同的过程(1 和 2)重复)。

在删除文件和文件夹时要小心。您可能想先打印出所有文件和文件夹的名称,而不是删除它们。一旦确认它工作正常,然后使用file.delete()。

【讨论】:

  • 这段代码的问题是它还删除了父文件。
  • @Siddharth 父文件是什么意思。你是说文件夹吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-02
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多