1

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

user2285526
  • 13
  • 1
  • 3

2 Answers2

4

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);
Sudhanshu Umalkar
  • 4,174
  • 1
  • 23
  • 33
0

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.

Pastho
  • 60
  • 2
  • 10