Question

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

Était-ce utile?

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

Autres conseils

Use this to read all files from a directory

File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();

Iterate over the listOfFiles and check with isDirectory() if the item is a directory. If yes you can use the same procedure to look into the sub-folders.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top