Reputation: 41
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<File> 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);
}
}
}
Upvotes: 4
Views: 6266
Reputation: 563
Maybe you should try walkFileTree method from NIO.2:
public List<Path> findAllFilesInDirectory(Path pathToDir) throws IOException {
final List<Path> pathsToFiles = new ArrayList<>();
Files.walkFileTree(pathToDir, new SimpleFileVisitor<Path>() {
@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:
http://docs.oracle.com/javase/tutorial/essential/io/walk.html
Tutorials:
http://www.javabeat.net/visiting-all-the-files-and-directories-for-a-directory-in-java-using-nio2/
http://www.srccodes.com/p/article/20/java-file-and-directory-operations-made-easy-in-jdk7
Upvotes: 4
Reputation: 347214
I have no issue with your code, but you might be running into issues with "symbolic links" (like "My Documents" on Windows) which, while they seem to appear as directories, Java can't resolve them and calling listXxx
will return null
.
Having said that, you could also try using something like...
public static void getAllFiles(File folder, List<File> result) {
System.out.println(folder.getName());
File[] listOfFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
if (listOfFiles != null && listOfFiles.length > 0) {
result.addAll(Arrays.asList(listOfFiles));
}
File[] listOfFolders = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File subFolder : listOfFolders) {
getAllFiles(subFolder, result);
}
}
instead to list the files and directories.
I believe the new nio2 (Files
and Paths
API) has a fix for it...
Upvotes: 1
Reputation: 341
I tried it as:
public void listf(String directoryName, List<File> files){
File directory = new File(directoryName)
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
files.add(file);
} else if (file.isDirectory()) {
listf(file.getAbsolutePath(), files);
}
}
}
Upvotes: 1