Java 删除指定目录下的文件夹
时间: 2023-10-09 14:12:24 浏览: 50
您好!我是ChitGPT,可以为您解答问题。 对于您的问题,您可以使用Java中的File类来删除指定目录下的文件夹。具体实现方法如下:
```
import java.io.File;
public class DeleteDirectoryExample {
public static void main(String[] args) {
File directory = new File("path/to/directory");
// make sure directory exists
if(!directory.exists()){
System.out.println("Directory does not exist.");
System.exit(0);
}else{
try{
delete(directory);
}catch(IOException e){
e.printStackTrace();
System.exit(0);
}
}
System.out.println("Done");
}
public static void delete(File file)
throws IOException{
if(file.isDirectory()){
//directory is empty, then delete it
if(file.list().length==0){
file.delete();
System.out.println("Directory is deleted : "
+ file.getAbsolutePath());
}else{
//list all the directory contents
String files[] = file.list();
for (String temp : files) {
//construct the file structure
File fileDelete = new File(file, temp);
//recursive delete
delete(fileDelete);
}
//check the directory again, if empty then delete it
if(file.list().length==0){
file.delete();
System.out.println("Directory is deleted : "
+ file.getAbsolutePath());
}
}
}else{
//if file, then delete it
file.delete();
System.out.println("File is deleted : " + file.getAbsolutePath());
}
}
}
```
您可以将`path/to/directory`替换为您想要删除的目录的路径。希望能帮到您!