JAVA list files in a directory

File class in java.io package contains methods to list files in a directory and also to determine if it is a directory or simply a file with a given filename. Here is a sample source code that list files in a given directory:

package com.javatutorialhq.sample;

import java.io.File;

public class DirectoryListing {
	/**
	* This java sample code shows how to list files
	* in a directory
	* Property of teknoscope.com
	* All Rights Reserved
	* Version 1.0
	* 05/09/2012
	*/
	public static void main(String[] args) {
		File file = new File("C:\\Notepad++");
		if(file.exists() && file.isDirectory()){
			String[] fileList = file.list();
			for(String s:fileList){
				System.out.println(s);
			}
		}
	}
}

Java List Files Sample Output:

change.log
config.model.xml
langs.model.xml
license.txt
localization
notepad++.exe
NppHelp.chm
NppHelp.chw
NppShell_04.dll
plugins
readme.txt
SciLexer.dll
shortcuts.xml
stylers.model.xml
themes
uninstall.exe
updater

The code file.exists() check if the pathname provided during invocation of the File constructor exists or not. The isDirectory() method in File class checks if the filename provided is a directory. The list() method returns an array of String denoting the contents of the abstract pathname declared during invocation of File constructor. Please be noted that if the pathnames is not a directory, the result list() is null that’s why there is a checker if the pathname is a directory by invoking the method isDirectory.