学 Java的第31天 递归遍历文件夹
package cn.aaa;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
public class Create {
public static void main(String[] args) throws IOException {
//创建文件夹
File f=new File("d:\\aaa");
boolean b=f.mkdirs();
System.out.println(b);
File f1=new File("d:\\aaa\\aaa.txt");
File f2=new File("d:\\aaa\\bbb.txt");
File f3=new File("d:\\aaa\\ddd.txt");
boolean b1=f1.createNewFile();
boolean b2=f2.createNewFile();
boolean b3=f3.createNewFile();
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
//递归
traverseFolder(null);
//普通方法
traverseFolder1(null);
}
private static void traverseFolder1(String path) {
int fileNum=0,folderNum=0;
File f=new File("d:\\aaa");
if(f.exists()){
LinkedList<File> list=new LinkedList<>();
File[] files=f.listFiles();
for (File file1 : files) {
if(file1.isDirectory()){
System.out.println("文件夹:"+file1.getAbsolutePath());
list.add(file1);
folderNum++;
}else{
System.out.println("文件"+file1.getAbsolutePath());
fileNum++;
}
}
File temp_file;
while(!list.isEmpty()){
temp_file=list.removeFirst();
files=temp_file.listFiles();
for (File file1 : files) {
if(file1.isDirectory()){
System.out.println("文件夹:"+file1.getAbsolutePath());
list.add(file1);
folderNum++;
}else{
System.out.println("文件:"+file1.getAbsolutePath());
fileNum++;
}
}
}
}else{
System.out.println("文件不存在");
}
}
public static void traverseFolder(String path) {
File f=new File("d:\\aaa");
if(f.exists()){
File[] files=f.listFiles();
if(null==files||files.length==0){
System.out.println("文件夹是空的!");
return;
}else{
for (File file : files) {
if(file.isDirectory()){
System.out.println("文件夹:"+file.getAbsolutePath());
traverseFolder(file.getAbsolutePath());
}else{
System.out.println("文件:"+file.getAbsolutePath());
}
}
}
}else{
System.out.println("文件不存在!");
}
}
}