Search code examples
javasubdirectoryfolderbrowserdialog

browsing folders in a folder


I want to open a folder which has multiple sub-folders in it. Each sub-folder has some files. I want to open a specific file number(lets say 3rd file in each folder) and manipulate it. Can someone help, since I am not able to figure it out from other threads.

Thanks in Advance


Solution

  • Please try the code below, it recursively iterates over the contents of the folder and lets you read/manipulate the 3rd file-

    public void openAndManipulateFile(final File root) {
    
        // get the list of files/folders
        final File[] files = root.listFiles();
        int counter = 0;
    
        for (File file : files) {
    
            // if its a directory, read its contents
            if (file.isDirectory()) {
                // recursive method call
                openAndManipulateFile(file);
            } else {
                if (++counter == 3) {
                    // open and manipulate the 3rd file
                }
            }
        }
    }
    

    To call it -

        File rootFolder = new File("some folder");
        openAndManipulateFile(rootFolder);