递归打印当前目录下所有层级的文件信息
作者:互联网
在Java中,File类提供有listFiles()方法,它能够列出本目录中的第一级信息
如果要求列出目录中所有级的信息,必须自己来处理。这种操作就必须通过递归的模式来完成。
递归打印当前目录下所有层级的文件信息:
import java.io.File;
public class Test{
public static void main(String[]args){
File file =new File("C:"+File.separator+"Users"+File.separator+"10320"+
File.separator+"ideaProjects");
listAllFiles(file);//从此处开始递归
}
public static void listAllFiles(File file){
if(file.isDirectory()){
File[] result=file.listFiles();
if(result!=null){//递归出口
for(File file2:result){
listAllFiles(file2);//继续递归的列出子目录
}
}
}else{
System.out.println(file);
}
}
}
运行结果:
C:\Users\10320\ideaProjects\File\.idea\description.html
C:\Users\10320\ideaProjects\File\.idea\misc.xml
C:\Users\10320\ideaProjects\File\.idea\modules.xml
C:\Users\10320\ideaProjects\File\.idea\project-template.xml
C:\Users\10320\ideaProjects\File\.idea\uiDesigner.xml
C:\Users\10320\ideaProjects\File\.idea\workspace.xml
C:\Users\10320\ideaProjects\File\File.iml
C:\Users\10320\ideaProjects\File\out\production\File\com\company\FileTest.class
C:\Users\10320\ideaProjects\File\out\production\File\com\company\Main.class
C:\Users\10320\ideaProjects\File\out\production\File\com\company\Test.class
C:\Users\10320\ideaProjects\File\out\production\File\TestFile.class
C:\Users\10320\ideaProjects\File\src\com\company\FileTest.java
C:\Users\10320\ideaProjects\File\src\com\company\Main.java
C:\Users\10320\ideaProjects\File\src\com\company\Test.java
C:\Users\10320\ideaProjects\File\src\com\company\TestIO.java
C:\Users\10320\ideaProjects\File\src\TestFile.java
C:\Users\10320\ideaProjects\project2\.idea\misc.xml
C:\Users\10320\ideaProjects\project2\.idea\modules.xml
C:\Users\10320\ideaProjects\project2\.idea\workspace.xml
C:\Users\10320\ideaProjects\project2\out\production\project2\Point.class
C:\Users\10320\ideaProjects\project2\out\production\project2\Test.class
C:\Users\10320\ideaProjects\project2\project2.iml
C:\Users\10320\ideaProjects\project2\src\Point.java
C:\Users\10320\ideaProjects\project2\src\Test.java
C:\Users\10320\ideaProjects\text.java
C:\Users\10320\ideaProjects\text.rtf
标签:10320,层级,Users,递归,ideaProjects,当前目录,idea,File,project2 来源: https://blog.csdn.net/Racheil/article/details/89146007