Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find sub-directories in a directory/folder?

Tags:

I'm looking for a way to get all the names of directories in a given directory, but not files.

For example, let's say I have a folder called Parent, and inside that I have 3 folders: Child1 Child2 and Child3.

I want to get the names of the folders, but don't care about the contents, or the names of subfolders inside Child1, Child2, etc.

Is there a simple way to do this?

like image 751
iaacp Avatar asked Nov 23 '12 17:11

iaacp


People also ask

How do I find sub directory?

Try find /dir -type d -name "your_dir_name" . Replace /dir with your directory name, and replace "your_dir_name" with the name you're looking for. -type d will tell find to search for directories only.

How do I list all subfolders in a directory?

Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.

Which command will find all the sub directories with directories?

The dir command displays a list of files and subdirectories in a directory. With the /S option, it recurses subdirectories and lists their contents as well.


2 Answers

If you are on java 7, you might wanna try using the support provided in

package java.nio.file  

If your directory has many entries, it will be able to start listing them without reading them all into memory first. read more in the javadoc: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path,%20java.lang.String)

Here is also that example adapted to your needs:

public static void main(String[] args) {     DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {         @Override         public boolean accept(Path file) throws IOException {             return (Files.isDirectory(file));         }     };      Path dir = FileSystems.getDefault().getPath("c:/");     try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {         for (Path path : stream) {             // Iterate over the paths in the directory and print filenames             System.out.println(path.getFileName());         }     } catch (IOException e) {         e.printStackTrace();     } } 
like image 154
Aksel Willgert Avatar answered Oct 19 '22 08:10

Aksel Willgert


You can use String[] directories = file.list() to list all file names, then use loop to check each sub-files and use file.isDirectory() function to get subdirectories.

For example:

File file = new File("C:\\Windows"); String[] names = file.list();  for(String name : names) {     if (new File("C:\\Windows\\" + name).isDirectory())     {         System.out.println(name);     } } 
like image 35
bhuang3 Avatar answered Oct 19 '22 07:10

bhuang3