Java - list all files in a folder

Posted on November 2, 2016


The below example shows how to list files in a folder using the listFiles() method of File class. The listFiles() method return files and folder names under a directory.

Here is an example of File.listFiles() method.

package com.boraji.tutorial.io;

import java.io.File;

/**
 * @author imssbora
 * ListFilesInDirectoryExample.java
 * Nov 2, 2016
 */
public class ListFilesInDirectoryExample {
	public static void main(String[] args) {
		File folder=new File("C:\\Program Files\\Java\\jdk1.8.0_71\\bin");
		
		/*Get files*/
		File[] files=folder.listFiles();
		for (File file : files) {
			if(file.isFile()){
				System.out.println("File : "+file.getName());
			}else{
				System.out.println("Folder : "+file.getName());
			}
		}
	}
}

Output

File : appletviewer.exe
File : extcheck.exe
File : idlj.exe
File : jabswitch.exe
File : jar.exe
File : jarsigner.exe
File : java-rmi.exe
File : java.exe
File : javac.exe
File : javadoc.exe
File : javafxpackager.exe
File : javah.exe
File : javap.exe
File : javapackager.exe
File : javaw.exe
File : javaws.exe
File : jcmd.exe
File : jconsole.exe
.....
.....