Search code examples
javadirectory-structure

Java: How to get only subdirectories name present at certain level?


Here is my folder structure:

parent/
  child1/
    child1.1/
    child1.2/
  child2/
    child 2.1/
    child 2.2/
  child3/
    child 3.1/
    child 3.2/

How can I extract only the names of the third-level folders? (I haven't been able to find this online)

Output should be:

child1.1 ,child1.2 
child2.1 ,child2.2
child3.1 ,child3.2

I referenced Java: how to get all subdirs recursively? to find subdirectories.


Solution

  • To make level parametric I suggest code:

    static public List<File> getDirs(File parent, int level){
        List<File> dirs = new ArrayList<File>();
        File[] files = parent.listFiles();
        if (files == null) return dirs; // empty dir
        for (File f : files){
            if (f.isDirectory()) {
                 if (level == 0) dirs.add(f);
                 else if (level > 0) dirs.addAll(getDirs(f,level-1));
            }
        }
        return dirs;
    }
    

    And call it:

    List<File> l = getDirs(new File("/some/path"), 3);
    

    Edit: I added verification in case of empty directory