List All Files In a Directory In Java

In this post we will see how to List all files in a directory in java . The class name File in java.io package have five different methods to get all files in directory and sub-directories in java . Now we will see examples for to read all files in folder .

File.list() Method Example

In this example we will get all files in directory and sub-directories in java using list() method of java.io.File . This method return an array of strings naming the files and directories in the given directory. Retrun array will be empty if the directory is empty. It Returns null if given pathname does not denote a directory, or if an I/O error occurs.

package com.demo.file;

import java.io.File;

public class ListOfFiles {
	
	public static void main(String[] args) {
		 //Creating a File object for directory
	       File directoryPath  = new File("C://java_examples");
	       
	       //store file and directory name in array
	        String[] files = directoryPath.list();
	 
	        //iterate array
	        for (String file : files)
	        {
	        	//print file or directory name
	            System.out.println(file);
	        }
	}

}

File.listFiles() Method Example

Now we will read all files in a directory using listFiles() method of java.io.File class. This method return an array of object of files and directories in the given directory . This method return object of file or directory , so we can access proprieties of file or directory like size , path etc.

package com.demo.file;

import java.io.File;

public class ListOfFiles2 {

	public static void main(String[] args) {
		 //Creating a File object for directory
		File directoryPath = new File("C://java_examples");

	    //store file and directory object in array
		File[] files = directoryPath.listFiles();

        //iterate array
		for (File file : files) {
		
			//print file or directory name 
			System.out.println(file.getName());
			System.out.println(file.getTotalSpace());
			System.out.println("==============");
		}
	}

}

List(FilenameFilter filter)  Method Example

This method return an array of strings naming the files and directories in the given directory . The behavior of this method is the same as that of the list() method, except that the strings in the returned array must satisfy the filter. We can get all files in directory with extension using lsit(FileNameFilter filter) . In this example we will get files name with .txt extension .

Parameters: It takes FileNameFilter as parameter .

Return :  It returns an array of strings naming the files and directories in the given directory , which  satisfy filter .

Exception : It throws SecurityException  If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory

package com.demo.file;

import java.io.File;
import java.io.FilenameFilter;

public class ListOfFiles3 {

	public static void main(String[] args) {
		//Creating a File object for directory
		File directoryPath = new File("C://java_examples");
	      FilenameFilter textFilefilter = new FilenameFilter(){
	         public boolean accept(File dir, String name) {
	            String lowercaseName = name.toLowerCase();
	            if (lowercaseName.endsWith(".txt")) {
	               return true;
	            } else {
	               return false;
	            }
	         }
	      };
	      //List of all the text files
	      String filesList[] = directoryPath.list(textFilefilter);
	      System.out.println("List of the text files in the given directory:");
	      for(String fileName : filesList) {
	         System.out.println(fileName);
	      }
		
	}
}

This java program read all files in directory with given .txt extension.

ListFiles(FilenameFilter filter) Method Example

It returns an array of object of files and directories in the given directory pathname that satisfy the specified filter.

Parameters: It takes parameter as filter FilenameFilter .
Returns: It returns an array of object of files and directories in the given directory pathname that satisfy the specified filter.. The array will be empty if the given directory is empty. Returns null if given pathname does not denote a directory, or if an I/O error occurs.
Exception : It throws SecurityException – If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory

package com.demo.file;

import java.io.File;
import java.io.FilenameFilter;

public class ListOfFiles4 {

	public static void main(String[] args) {

		// Creating a File object for directory
		File directoryPath = new File("C://java_examples");
		FilenameFilter textFilefilter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				String lowercaseName = name.toLowerCase();
				if (lowercaseName.endsWith(".txt")) {
					return true;
				} else {
					return false;
				}
			}
		};
		// List of all the text files
		File filesList[] = directoryPath.listFiles(textFilefilter);
		System.out
		.println("List of the text files in the specified directory:");
		for (File file : filesList) {
			//print file or directory properties  
			System.out.println(file.getName());
			System.out.println(file.getTotalSpace());
			System.out.println("==============");
		}

	}

}

File.listFiles(FileFilter filter) Method Example

This method takes FileFilter as parameter . It returns an array of object of files and directories in the given directory pathname that satisfy the specified filter.

package com.demo.file;

import java.io.File;
import java.io.FileFilter;

public class ListOfFiles5 {
	public static void main(String[] args) {

		File directoryPath = new File("C://java_examples");

		// Implementing FileFilter to retrieve the files smaller than 5MB

		FileFilter sizeFilter = new FileFilter() {
			@Override
			public boolean accept(File file) {
				if (file.length() < 5 * 1024 * 1024) {
					return true;
				} else {
					return false;
				}
			}
		};

		// Passing sizeFilter to listFiles() method

		File[] files = directoryPath.listFiles(sizeFilter);

		for (File file : files) {
			System.out.println(file.getName());
		}
	}
}

In this tutorial we have learned various method to list all files in a directory . We have also seen example for get all files in directory and sub-directories and get all files in directory with extension also . If you want to learn more about file manipulation  , then i recommended to you read file file handling in java .

 

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 31 = 33