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?
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.
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.
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.
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(); } }
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With