Get the number of folders in data path

edited August 2014 in How To...

Hi all,

I would like to return the number of folders in a specific path. Say I have a 'masks' folder in the data folder. This 'masks' folder can itself contain any number of folders and I need the program to respond to that number. How can I retrieve this quantity of folders as an int?

Tagged:

Answers

  • Answer ✓

    Almost a classical, with a twist, though.

    You should take a look at the File Java class. It has everything you need.

    Well, you also need to call dataFile("") to get the File object corresponding to the data folder.

    Basically, you need listFiles() to get a list of the files (including folders) in the data folder, then isDirectory() to distinguish folders from plain files, then iterate on the found folders to see if they contain folders too, etc.

  • edited August 2014

    Thanks a lot! For anyone as noob as me, here's the small method I came up with.

      public int getFolders() {
        int folders = 0;
        java.io.File folder = new java.io.File(dataPath(""));
        String[] list = folder.list();
    
        for (int i=0; i<list.length; i++) {
          java.io.File current_item = new java.io.File(dataPath("" + list[i]));
          if (current_item.isDirectory()) {
            folders++;
            println("item " + i + " (" + list[i] + ") is a directory");
          } 
          else {
            println("item " + i + " (" + list[i] + ") is NOT a directory");
          }
        }
        println("Total number of directories found is " + folders);
        println("Thanks to PhiLho on the Processing forums!");
        return folders;
      }
    }
    
  • edited August 2014

    Alternative version using FileFilter + listFiles() in order to recursively get a folders-only List: :bz

    /**
     * Get All Sub-Folders (v1.11)
     * by GoToLoop (2014/Aug)
     *
     * forum.processing.org/two/discussion/6712/
     * get-the-number-of-folders-in-data-path
     *
     * forum.processing.org/two/discussion/6677/
     * splitting-a-text-file-using-crlf-and-parsing-file-
     */
    
    import java.util.List;
    import java.io.FileFilter;
    
    static final FileFilter FOLDER_FILTER = new FileFilter() {
      @ Override boolean accept(File path) {
        return path.isDirectory();
      }
    };
    
    File[] dirs;
    
    void setup() {
      boolean gotParam = args.length > 0 && !args[0].startsWith("--");
      String path = gotParam? args[0] : dataPath("");
    
      if ((dirs = getAllFolders(path)) == null || dirs.length == 0) {
        println("Got no folders in \"" + path + "\"\n");
        exit();
        return;
      }
    
      println("Found " + dirs.length + " folder(s) in \"" + path + "\"\n");
      println(dirs);
    
      exit();
    }
    
    static final File getAllFolders(String dirPath)[] {
      File f = new File(dirPath);
      if (!f.isDirectory()) {
        println("\nPath \"" + dirPath + "\" isn't a folder!\n");
        return null;
      }
    
      List<File> folders = new ArrayList();
      recursiveFolders(f, folders);
    
      return folders.toArray( new File[folders.size()] );
    }
    
    static final void recursiveFolders(File dirPath, List<File> folders) {
      for (File dir: dirPath.listFiles(FOLDER_FILTER)) {
        folders.add(dir);
        recursiveFolders(dir, folders);
      }
    }
    
  • Good idea to use a filter, I should have remembered this... :-) It cuts down the code.
    Moxl, your code is OK if you don't have nested folders, otherwise, use GoToLoop's one.

    Note that I suggested to use dataFile() instead of dataPath(), that would avoid to wrap the result in a File() constructor... Idem for listFiles() instead of list().

  • edited August 2014

    I didn't know about dataFile("") which returns a File instead of a String as dataPath("") does! *-:)
    Although it's somewhat useless, b/c Processing's IO functions accepts String references only! :(
    I wish the devs would write overloaded File versions for all of them too! :-<

  • edited August 2014

    @Moxl, your code is OK if you don't have nested folders,...

    Actually, his only got folders inside "/data/". If there are any deeper subfolders within them, they're ignored.
    Nonetheless, I did a shorter version of his using dataFile("") + listFiles() w/o any FileFilter: B-)

    // forum.processing.org/two/discussion/6712/
    // get-the-number-of-folders-in-data-path
    
    int getNumDataFolders() {
      int count = 0;
      for ( File f: dataFile("").listFiles() )
        if (f.isDirectory())  ++count;
      return count;
    }
    
    void setup() {
      int num = getNumDataFolders();
      println(num);
      exit();
    }
    
  • "it's somewhat useless"
    Not if you need to do pure File operations as we describe above!
    Doing new File(dataPath("")); actually invokes dataFile(), then extract the path out of it, to wrap it again in a new object...

    "his only got folders inside "/data/". If there are any deeper subfolders within them, they're ignored."
    It thought that's what I wrote and what you quoted? Is my English so bad?

  • Wow thanks for all the development in replies. I'll try to wrap my head around this when I get the chance.

Sign In or Register to comment.