Sam
Sam

Reputation: 1269

How to open and display content of multiple files in folder with multiple folder?

I have folders with multiple files. This is how the organization is.

Folder_1
  - Folder_1_File_1
  - Folder_1_File_2
  - Folder_1_File_3
  - Folder_1_File_4
  ...
Folder_2
  - Folder_2_File_1
  - Folder_2_File_2
  - Folder_2_File_3
  - Folder_2_File_4
  ...
Folder_3
  - Folder_3_File_1
  - Folder_3_File_2
  - Folder_3_File_3
  - Folder_3_File_4
  ...

I have to open each folder, read each file and then perform some computations on all files of each folder and display result, then move to next folder and perform same computations on files of those folders. Below is my code. Is there any other easier method to do it? My code is really slow and sometimes it doesn't even work.

public void listFilesForFolder_Test(final File folder) {
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                listFilesForFolder_Test(fileEntry);
            } else {

                Test_filenames.add(fileEntry.getAbsolutePath());
                Test_filename.add(fileEntry.getName());
                //  String content = FileUtils.readFileToString(file);
                 // read file and perform computations on it.

            }
        }
    } 

Upvotes: 3

Views: 1710

Answers (2)

Rafik
Rafik

Reputation: 455

This code will provide you regular files (not folders) at first the walk the rest of the given path tree.

public class ReadRecurssivelyFromFolder {


public static void main(String[] args) {
    try {
        Files.walk(Paths.get("/home/rafik/test" ))
                .filter(Files::isRegularFile)
                .forEach(System.out::println);

    } catch (IOException ex) {
        Logger.getLogger(ReadRecurssivelyFromFolder.class.getName()).log(Level.SEVERE, null, ex);
    }
}

OUTPUT:

enter image description here

Then you can perform your calculation based on the given paths.

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299148

Java 8 has introduced the Visitor-based Files.walkFileTree() api which is a lot easier to master:

File file = new File("/base/folder");
Files.walkFileTree(file.toPath(), new SimpleFileVisitor<>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        // do your thing here
        return FileVisitResult.CONTINUE;
    }
});

Upvotes: 4

Related Questions