Java - Iterate over all files in directory

Aishu :

I want to find all the txt files in directory and in the nested sub-directories. If found, I want to move that from one location to another.

The below code works fine, if i don't have any nested sub-directories.

The problem with the below code is, Once it find the nested directories it return the file only from that particular nested sub-directory. But I want all the txt files in my directory ( parent and its nested sub-directories ).

public class FilesFindingInDirectory {
    static ArrayList<File> al = new ArrayList<File>();
    static File fileLocation = null;
    public static void main(String[] args) throws IOException {


        File filePath = new File("C:\\Users\\Downloads");

        File[] listingAllFiles = filePath.listFiles();

        ArrayList<File> allFiles = iterateOverFiles(listingAllFiles);


                for (File file : allFiles) {
                    if(file != null) {
                        String fileName = file.getName();

                        String sourceFilepath = file.getAbsolutePath();
                        File targetFilePath = new File("D:\\TestFiles");
                        String targetPath = targetFilePath.getPath();

                        Files.move(Paths.get(sourceFilepath), Paths.get("D:\\TestFiles\\" + fileName)); 
                    }

                }
            }


public static ArrayList<File> iterateOverFiles(File[] files) {


        for (File file : files) {

            if (file.isDirectory()) {

                iterateOverFiles(file.listFiles());// Calls same method again.

            } else {

                fileLocation = findFileswithTxtExtension(file);
                if(fileLocation != null) {
                    System.out.println(fileLocation);
                    al.add(fileLocation);
                }


            }
        }

        return al;
    }

public static File findFileswithTxtExtension(File file) {

        if(file.getName().toLowerCase().endsWith("txt")) {
            return file;
        }

        return null;
    }
}
Mureinik :

You are properly calling the function recursively, but you're then ignoring its return value. Instead, you should append it to the result list:

public static List<File> iterateOverFiles(File[] files) {
    List<File> result = new ArrayList<>();
    for (File file : files) {
        if (file.isDirectory()) {
            result.addAll(iterateOverFiles(file.listFiles()); // Here!
        } else {
            fileLocation = findFileswithTxtExtension(file);
            if(fileLocation != null) {
                result.add(fileLocation);
            }
        }
    }

    return result;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471754&siteId=1