Java list directories


 

Java list directories

In this section, you will learn how to display the list of directories from a particular directory.

In this section, you will learn how to display the list of directories from a particular directory.

Java list directories

In this section, you will learn how to display the list of directories from a particular directory.

Description of code:

As you all know java.io.* packages works with both files and directories. So here we have used the methods of File class to retrieve the list of directories from the particular directory.

In the given example, we have created an object of File class and parse the directory through the constructor of the File class. Then we have called listFiles() method which actually returns the array of both the file and directory names. So in order to get only the directories, we have created a condition that if the array of files contains directory, then display its name.

getName(): This method of File class returns the name of file or directory.

listFiles(): This method of File class  returns an array of all the files and directories of the specified directory.

Here is the code:

import java.io.*;

public class FileListDirectories {
	public static void main(String[] args) {
		File dir = new File("C:/");
		File listDir[] = dir.listFiles();
		for (int i = 0; i < listDir.length; i++) {
			if (listDir[i].isDirectory()) {
				System.out.println(listDir[i].getName());
			}
		}
	}
}

Ads