列出目录:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MyUtil {
// 工具类中的方法都是静态方式访问的因此将构造器私有不允许创建对象(绝对好习惯)
private MyUtil() {
throw new AssertionError();
}
public static List listDirectories(String directoryName) {
List aList = new ArrayList();
File file = new File(directoryName);
for (File temp : file.listFiles()) {
if (temp.isDirectory()) {
System.out.println(temp.toString());
aList.add(temp.toString());
}
}
return aList;
}
public static void main(String[] args) {
List aList = new ArrayList();
System.out.println(MyUtil.listDirectories("F:\\WorkSpace feature\\rule_center\\target\\classes\\"));
}
}
列出文件:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MyUtil {
// 工具类中的方法都是静态方式访问的因此将构造器私有不允许创建对象(绝对好习惯)
private MyUtil() {
throw new AssertionError();
}
public static List listFiles(String directoryName) {
List aList = new ArrayList();
File file = new File(directoryName);
for (File temp : file.listFiles()) {
if (temp.isFile()) {
System.out.println(temp.toString());
aList.add(temp.toString());
}
}
return aList;
}
public static void main(String[] args) {
List aList = new ArrayList();
System.out.println(MyUtil.listFiles("F:\\WorkSpace feature\\rule_center\\target\\classes\\"));
}
}
改进:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MyUtil {
// 工具类中的方法都是静态方式访问的因此将构造器私有不允许创建对象(绝对好习惯)
private MyUtil() {
throw new AssertionError();
}
public static List listFile(String directoryName) {
List aList = new ArrayList();
File file = new File(directoryName);
for (File temp : file.listFiles()) {
if (temp.isDirectory()) {
MyUtil.listFile(temp.toString()); //递归进一步查找目录里的文件和目录
System.out.println("目录:" +temp.toString());
aList.add(temp.toString());
} else {
System.out.println("文件:"+temp.toString());
aList.add(temp.toString());
}
}
return aList;
}
public static void main(String[] args) {
List aList = new ArrayList();
System.out.println(MyUtil.listFile("F:\\WorkSpace feature\\rule_center\\target\\classes\\system\\"));
}
}