Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listFiles() in Java fails to get all files

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);
        }
    }
}
like image 806
Stanislav Bozhanov Avatar asked Oct 20 '25 01:10

Stanislav Bozhanov


2 Answers

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

like image 152
Daniel Michalski Avatar answered Oct 21 '25 15:10

Daniel Michalski


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); } } }

like image 21
Abhi Avatar answered Oct 21 '25 13:10

Abhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!