I am trying to get the names of all of the text files in a directory. If the directory has subdirectories then I also want to get any text files in those as well. I am not sure how to make the process continue for any number of subdirectories.
Right now the code below just gets all the text files in the current directory and and subdirectories in the directory. For each subdirectory found, it also finds any text files and deeper subdirectories. The problem is that if those deeper subdirectories have yet deeper subdirectories then I am not finding all the text files. This seems to be a problem that requires recursion because I don't know how deep this will go.
Here is my code so far:
File rootDirectory = new File(rootDir);
if (rootDirectory.isDirectory()) {
System.out.println("Valid directory");
File[] listOfFiles = rootDirectory.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile()) {
if (iName.endsWith(".txt") || iName.endsWith(".TXT")) {
System.out.println("File: "+iName);
}
}
if (listOfFiles[i].isDirectory()) {
System.out.println("Directory: "+iName);
File[] subList = listOfFiles[i].listFiles();
for (int j = 0; j < subList.length; j++) {
String jName = subList[j].getName();
if (subList[j].isFile()) {
if (jName.endsWith(".txt") || jName.endsWith(".TXT")) {
System.out.println("File: "+jName);
}
}
if (subList[j].isDirectory()) {
System.out.println("Directory: "+jName);
}
}
}
}
}
else System.out.println("Invalid directory");
Edit: Got it working, thank you Olaf Dietsche:
public void findFiles(File root, int depth) {
File[] listOfFiles = root.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile()) {
if (iName.endsWith(".txt") || iName.endsWith(".TXT")) {
for (int j = 0; j < depth; j++) System.out.print("");
System.out.println("File: "+iName);
}
}
else if (listOfFiles[i].isDirectory()) {
for (int j = 0; j < depth; j++) System.out.print("");
System.out.println("Directory: "+iName);
findFiles(listOfFiles[i], depth+1);
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…