gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:37:33 25 4
gpt4 key购买 nike

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

}

最佳答案

您可以将"new"Java 文件 API 与流 API 一起使用:

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

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

关于一条语句,并且没有任何第三方库 ;)

关于Java - 递归删除父路径的文件和文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com