Java - Iterate over all files in a directory

I want to find all the files txtin a directory and in subdirectories. If found, I want to move it from one place to another.

The code below works fine if I don't have any subdirectories.

The problem with the code below is that when it finds the subdirectories, it returns the file only from this subdirectory. But I want all the txtfiles in my directory (the parent and its subdirectories).

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;
    }
}
+4
source share
4 answers

You correctly call the function recursively, but then ignore its return value. Instead, you should add it to the list of results:

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;
}
+1
source

:

return al;

, :

ArrayList<File> allFiles = iterateOverFiles(listingAllFiles);

to

iterateOverFiles(listingAllFiles);

, , for al.

for (File file : allFiles) {

to

for (File file : al) {

: . . . .

+3

API nio , ?

 List<Path> txtFiles = Files.walk(Paths.get("C:\\Users\\Downloads"))
                            //use to string here, otherwise checking for path segments
                            .filter(p -> p.toString().endsWith(".txt"))
                            .collect(Collectors.toList());

, foreach

Files.walk(Paths.get("C:\\Users\\Downloads"))
     .filter(p -> p.toString().endsWith(".txt"))
     .forEach(p -> {
        try {
            Files.move(p, Paths.get("D:\\TestFiles", p.getFileName().toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
+3

, , . .

public class FilesFindingInDirectory {
   public static void main(String[] args) throws IOException {


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


    Collection<File> allFiles = findFiles(filePath, ".txt");
    allFiles.forEach(file -> {
                    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 List<File> findFiles(File dir, String extension) {
    File[] files = dir.listFiles(f -> f.isDirectory() || f.getName().toLowerCase().endsWith(extension);
    ArrayList<File> result = new ArrayList<>();  
    if (files != null) {
       for (File file : files) {

        if (file.isDirectory()) {
            result.addAll(findFiles(file, extension);
        } else {
            result.add(file);
        }

    }

    return result;
  }
}
0

Source: https://habr.com/ru/post/1696184/


All Articles