[英]How to delete empty directories recursively without deleting parent folder?
[英]Java - Deleting files and folder of parent path recursively
我正在创建一个采用父路径并删除给定路径中的所有文件和文件夹的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;
}
}
您应该考虑使用Apache Commons-IO 。 它具有FileUtils类,该类具有将递归删除的deleteDirectory方法。
注意: Apache Commons-IO(从2.5版开始)仅为旧版java.io
API( File
和朋友)提供实用程序,而不为Java 7+ java.nio
API( Path
和朋友)提供实用程序。
您可以将““新”” 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()
方法的调用是删除目录之前的所有文件。
关于一个声明,并且没有任何第三方库;)
您可以递归地遍历该文件夹并逐个删除每个文件。 删除一个文件夹中的所有文件后,删除该文件夹。 类似以下代码的东西应该起作用:
public void delete(File path){
File[] l = path.listFiles();
for (File f : l){
if (f.isDirectory())
delete(f);
else
f.delete();
}
path.delete();
}
您可以执行以下操作,您的递归比需要的时间更长。
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();
}
说明:
当在文件上调用deleteFiles()
时,else语句将被触发,单个文件将被删除而不会递归。
在文件夹上调用deleteFiles()
时,会触发if语句。
实施删除文件和文件夹时要小心。 您可能需要先打印出所有文件和文件夹的名称,而不是删除它们。 一旦确认它可以正常工作,然后使用file.delete()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.