directory traversal in Java using different regular and enhanced for loops
- by user3245621
I have this code to print out all directories and files. I tried to use recursive method call in for loop. With enhanced for loop, the code prints out all the directories and files correctly. But with regular for loop, the code does not work. I am puzzled by the difference between regular and enhanced for loops.
public class FileCopy {
private File[] childFiles = null;
public static void main(String[] args) {
FileCopy fileCopy = new FileCopy();
File srcFile = new File("c:\\temp");
fileCopy.copyTree(srcFile);
}
public void copyTree(File file){
if(file.isDirectory()){
System.out.println(file + " is a directory. ");
childFiles = file.listFiles();
/*for(int j=0; j<childFiles.length; j++){
copyTree(childFiles[j]);
}
This part is not working*/
for(File a: childFiles){
copyTree(a);
}
return;
} else{
System.out.println(file + " is a file. ");
return;
}
}
}