Java 创建、读取、删除目录
-
创建目录 import java.io.File
public class CreateFileDir {
pubulic void main(String[] args) {
String dirName = "Test";
File d = new File(dirName);
d.mkdirs();
}
}
-
读取目录 import java.io.File
public class ReadFileDir {
public void main(String[] args) {
String dirName = "Test";
File f1 = new File(dirName);
if(f1.isDirectory()) {
System.out.println("目录 " + dirName);
String[] s = f1.list();
for (String value : s) {
File f = new File(dirName + "/" + value);
if (f.isDirectory()) {
System.out.println(value + "是一个目录");
} else {
System.out.println(value + "是一个文件");
}
}
}else {
System.out.println(dirName + "不是一个目录");
}
}
}
-
删除目录或文件 public class DeleteDir {
public static void main(String[] args) {
File folder = new File("Test");
File[] files = folder.listFiles();
boolean a;
if (files != null) {
for (File f : files) {
a = f.delete();
if(a) {
System.out.println("删除成功" + f);
}else {
System.out.println("删除失败,因为目录不为空:" + f);
}
}
}
a = folder.delete();
if(a) {
System.out.println("删除成功:" + folder);
}else {
System.out.println("删除失败:" + folder + " 目录不为空");
}
}
}
|