//该方法不在控制台中运行。 我试图在main中初始化它,但没有任何效果 目的是编写一个递归方法查找并列出目录和子目录,并在没有目录时停止。
package Folders;
import java.io.File;
//lists
//isFile
/**/
public class Main {
public static void main(String[] args) {
// Object directoryName;
// TODO Auto-generated method stub
// String listFilesAndFilesSubDirectories a = new
// listFilesAndFilesSubDirectories();
/*
* listFilesAndFilesSubDirectories a = new
* listFilesAndFilesSubDirectories(); System.out.println(); File file1 =
* new File("C:\\"); String[] files = file1.list(); for(String string :
* files) { System.out.println(string); }
*/
}
public class listFilesAndFilesSubDirectories {
public void listFilesAndFilesSubDirectories(String directoryName) {
// directoryName = "C:\\";
File file1 = new File("C:\\");
String[] files = file1.list();
for (String string : files) {
System.out.println(string);
}
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
System.out.println("fdadfa");
} else if (file.isDirectory()) {
listFilesAndFilesSubDirectories(file.getAbsolutePath());
} else {
break;
}
}
}
}
}
答案 0 :(得分:0)
要在目录中递归打印文件名,请按以下方式更改方法: -
public static void listFilesAndFilesSubDirectories(File directoryName) throws Exception {
for(File file : directoryName.listFiles()) {
if(file.isDirectory())
listFilesAndFilesSubDirectories(file);
else if(file.isFile())
System.out.println(file.getName());
}
}