在Java程序中,如何确定一个目录是否为空?
以下示例使用File
类的file.isDirectory()
,file.list()
和file.getPath()
方法获取目录的大小。
package com.yiibai;
import java.io.File;
public class EmptyDirectory {
public static void main(String[] args) {
String dir = "F:/worksp/javaexamples/java_directories/dir11";
File file = new File(dir);
if (file.isDirectory()) {
String[] files = file.list();
if (files.length > 0) {
System.out.println("The " + file.getPath() + " is not empty!");
for(String str : files){
System.out.println("Exsits file: " + str);
}
}else{
System.out.println("The " + file.getPath() + " is empty!");
}
}
}
}
执行上面示例代码,得到以下结果 -
The F:\worksp\javaexamples\java_directories\dir11 is not empty!
Exsits file: dir12
Exsits file: file1 - 副本.txt
Exsits file: file1.txt