本例以Windows, JDK1.7 为基础,来演示使用Java 目录(文件夹)的删除。

目录和文件的删除都是会使用到File.delete();,但是在目录的删除上面,如果目录为空则可以删除,如果目录不为空则删除会失败。这时候需要先删除目录下面的文件,然后再来删除目录。

删除目录

FileDeleteDirectory.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.devnp.io;

import java.io.File;

public class FileDeleteDirectory {

public static void main(String[] args) {
// TODO Auto-generated method stub

File file = new File("D:\\Person-Test\\temp\\1");

deleteDirectory(file);
}

public static void deleteDirectory(File file) {

if (file.isDirectory()) {
//如果目录为空,则直接删除
if (file.list().length == 0) {
file.delete();

System.out.println("Directory is deleted : " + file.getAbsolutePath());
} else {
File [] files = file.listFiles();

for (File temp : files) {
deleteDirectory(temp);
}

//当删除完成目录下面的所有文件,再来删除目录本身
if (file.list().length == 0) {
file.delete();
System.out.println("Directory is deleted : " + file.getAbsolutePath());
}
}
} else {
//删除文件
file.delete();

System.out.println("File is deleted : " + file.getAbsolutePath());
}
}

}
运行:
测试:以删除D:\\Person-Test\\temp\\1目录为例
1
2
3
4
5
File is deleted : D:\Person-Test\temp\1\New folder\New folder\New Text Document.txt
Directory is deleted : D:\Person-Test\temp\1\New folder\New folder
Directory is deleted : D:\Person-Test\temp\1\New folder
Directory is deleted : D:\Person-Test\temp\1\New folder (2)
Directory is deleted : D:\Person-Test\temp\1

相关

  1. java-file-create-directory-创建目录(文件夹)