因为发现file.list()只能获取一级目录下的文件或文件夹,不能适用于业务需求,所以编写了一个工具类,方便以后使用
public static List<File> readfile(String path) throws FileNotFoundException, IOException {
try {
List<File> fileList=new ArrayList<>();
File file = new File(path);
if (!file.isDirectory()) {
fileList.add(file);
} else if (file.isDirectory()) {
String[] files = file.list();
for (int i = 0; i < files.length; i++) {
File newFile = new File(path + "\\" + files[i]);
if (!newFile.isDirectory()) {
fileList.add(newFile);
} else if (newFile.isDirectory()) {
readfile(path + "\\" + files[i],fileList);
}
}
}
} catch (FileNotFoundException e) {
System.out.println("readfile() Exception:" + e.getMessage());
}
return fileList;
}
根据传入的文件夹路径,获取目录下所以文件(夹),逐一判断,如果是文件添加进集合fileList中,否则自调用函数,继续判断,直至所有文件遍历完毕并添加进集合中,最后将集合返回给方法调用处。