I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.
import java.io.*;
public class RecursiveDir {
static BufferedReader br = new BufferedReader(new开发者_开发技巧 InputStreamReader(System.in));
public static void main(String[]args) throws IOException {
System.out.print("Please enter a directory name: ");
File f = new File(br.readLine());
FileFilter filter = new FileFilter() {
public boolean accept(File f) {
if(f.isDirectory()) {
return true;
}
return false;
}
};
File[] list = f.listFiles(filter);
System.out.println(returnDir(list,list.length));
}
public static File returnDir(File[] file,int counter) {
File f = file[counter];
if(counter == 0) {
return file[0];
}else {
return f = returnDir(file,counter--);
}
}
}
EDIT: I followed the comments below and changed return f = returnDir(file,counter--);
to
return f = returnDir(file,--counter);
and also changed returnDir(list,list.length);
to
returnDir(list,list.length-1);
, my code runs fine but now nothing is printing.
You are going out of the array bound because you need to pass list.length - 1
to the method.
Even if you did that, though, you would have an infinite recursion, because counter--
will use the value of counter, and then decrement it. So that means you are calling returnDir
with the current value of counter.
Use either --counter
, or counter - 1
.
What do expect to happen here? You don't seem to be doing anything with the files as you visit them. There is no need for recursion to loop through the files in the directory, the recursion is needed when you hit a file in the list that is a directory.
You are indeed going out of bounds. You need to change
returnDir(list,list.length);
to
returnDir(list,list.length - 1 );
You seem to be missing your System.out.println() calls. You are looping through the files and not doing anything with them.
Your initial call to returnDir should be
returnDir(list,list.length-1);
Paul
精彩评论