I wrote this function and it seemed okey but it fails if there are more than one folders in the current directory and no files. It enters only the first folder and does it job there and ignores the other folders. How can I fix this bug?
public static void getAllFiles(File folder, List result) {
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
result.add(listOfFiles[i]);
}
if (listOfFiles[i].isDirectory()) {
getAllFiles(listOfFiles[i], result);
}
}
}
解决方案
Maybe you should try walkFileTree method from NIO.2:
public List findAllFilesInDirectory(Path pathToDir) throws IOException {
final List pathsToFiles = new ArrayList<>();
Files.walkFileTree(pathToDir, new SimpleFileVisitor() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (Files.isRegularFile(file)) {
pathsToFiles.add(file);
}
return FileVisitResult.CONTINUE;
}
});
return pathsToFiles;
}
To using NIO.2 You have to have at least a Java 1.7 version.
Documentation:
Tutorials: