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;
}
}
答案 0 :(得分:6)
您应该考虑使用Apache Commons-IO。它有一个FileUtils类,其方法是deleteDirectory,它将以递归方式删除。
注意: Apache Commons-IO(与2.5版一样)仅为旧版java.io
API(File
和朋友)提供实用程序,而不是Java 7+ {{ 1}} API(java.nio
和朋友)。
答案 1 :(得分:6)
您可以使用“”新的“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 );
请注意,调用sorted()
方法是为了删除目录之前的所有文件。
关于一个声明,没有任何第三方库;)
答案 2 :(得分:3)
您可以递归遍历文件夹并逐个删除每个文件。删除一个文件夹中的所有文件后,删除该文件夹。类似于以下代码的东西应该有效:
public void delete(File path){
File[] l = path.listFiles();
for (File f : l){
if (f.isDirectory())
delete(f);
else
f.delete();
}
path.delete();
}
答案 3 :(得分:0)
您可以执行以下操作,递归时间比需要的时间长。
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()
。