How to get the content of a directory in java

This example shows you how to read the list of files inside the current directory in java.

You can get the list of file you can use the the File.listFiles() method. This method return an array of File object which can be either an instance of file or directory.

Below is the example code.

package com.java.connect.io;

import java.io.File;

//How to get the content of a directory in java
public class DirectoryContentExample {

	public static void main(String[] args) {
		File dirContent = new File("E:\\WORK\\projects\\java-connect-example");

		// You can get the list of files under the specified directory
		// above and return it as an abstract file object.
		File[] dirfiles = dirContent.listFiles();

		// You need to iterates to know file is directory or file.
		for (File file : dirfiles) {
			System.out.println(file + " : This is a "
					+ (file.isDirectory() ? "directory" : "file"));
		}

		// You can get only the files inside the directory
		// using dirContent calling by list method.
		// This method returns the array of String which
		// Content the names of file
		String[] files = dirContent.list();
		for (String file : files) {
			System.out.println("The file is : " + file);
		}

	}
}