directory traversal in Java using different regular and enhanced for loops
Posted
by
user3245621
on Stack Overflow
See other posts from Stack Overflow
or by user3245621
Published on 2014-06-10T03:20:46Z
Indexed on
2014/06/10
3:24 UTC
Read the original article
Hit count: 134
java
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;
}
}
}
© Stack Overflow or respective owner