Oct 12, 2013

Get list of File and Directory in Java - list() and listFiles() method in Java

Java provides list() and listFiles() methods in File class to display all file/directory names as well as getting File objects in the given directory.
list() - Returns list of files and directory names (String[] - Array of string objects is returned )
listFiles() - Returns list of files and directory (File[] - Array of File objects is returned )
Note:- In Java, whether it is file or directory, internally both are File Object.File class provides isDirectory() and isFile() method to check whether it is fie of directory.
Below sample program displays list of file/directory names and also display absolute path after retrieving list of files.
import java.io.File;

public class ListFileOrDirNames {
 public static void main(String[] args) {
  File dirPath = new File("E:\\software");
  // Display Files And Directory names - String Object return
  String[] fileNamelist = dirPath.list();
  System.out.println("*******File/Directory names**********");
  for (String fileName : fileNamelist) {
   System.out.println(fileName);
  }

  // Get Files And Directory - File object return
  File[] fileList = dirPath.listFiles();
  System.out.println("*******File/Directory absolute path******");
  for (File file : fileList) {
   System.out.println(file.getAbsoluteFile());
  }
 }

}
========Sample output===============
*******File/Directory names**********
apache-tomcat-7.0.62-windows-x86
apache-tomcat-7.0.62-windows-x86.zip
error while installing WAMP
Sandbox_HDP_2.2.4.2_VMWare.ova
ubuntu-14.04.3-desktop-amd64.iso
wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-32b.exe
wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-64b.exe
xp

*******File/Directory absolute path******
E:\software\apache-tomcat-7.0.62-windows-x86
E:\software\apache-tomcat-7.0.62-windows-x86.zip
E:\software\error while installing WAMP
E:\software\Sandbox_HDP_2.2.4.2_VMWare.ova
E:\software\ubuntu-14.04.3-desktop-amd64.iso
E:\software\wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-32b.exe
E:\software\wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-64b.exe
E:\software\xp
================================
Location: Coimbatore, Tamil Nadu, India