Home Tutorial Java Core Files Java list directories

 
 

Java list directories
Posted on: August 5, 2006 at 12:00 AM
Advertisement
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());
			}
		}
	}
}
Advertisement

Related Tags for Java list directories:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 5, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com