Not much to say, just go to the code
import java.io.File;
public class file { public static void main(String[] args){ File file=new File("C:/HWKJ/file"); filesDirs(file); } //Use recursive traversal of files in folders and subfolders public static void filesDirs(File file){ //The File object is the path of a file or folder, the first layer judges whether the path is empty if(file!=null){ //The second layer path is not empty, it is judged to be a file Folder or file if(file.isDirectory()){ //Enter here to indicate that it is a folder. At this time, you need to get all the files under the current folder, including the directory File[] files=file.listFiles();//Note: here You can only use listFiles(), not list() //All the contents under files may be folders or files, so you need to judge whether it is a file or a folder one by one. This judgment process is the method encapsulated here //So you can call yourself to judge and implement recursion for (File flies2:files) {
filesDirs(flies2);
}
}else{ System.out.println("file name"+file); } }else{ System.out.println("file does not exist"); }
}
}