Difference between the list() and listFiles() methods in Java

JavaObject Oriented ProgrammingProgramming

The class named File of the java.io package represents a file or directory (path names) in the system. To get the list of all the existing files in a directory this class provides the list() and ListFiles() methods.

The main difference between them is that

  • The list() method returns the names of all files in the given directory in the form of a String array.

  • The ListFiles() method returns the objects (File) of the files in the given directory, in the form of an array of type File.

i.e. If you just need the names of the files within a particular directory you can use the list() method and, if you need the details of the files in a directory such as name, path etc. you need to use the ListFiles() method, retrieve the objects of all the files and get the required details by invoking the respective methods.

list() method Example

import java.io.File;
import java.io.IOException;
public class ListOfFiles {
   public static void main(String args[]) throws IOException {
      //Creating a File object for directory
      File path = new File("D:\\ExampleDirectory");
      //List of all files and directories
      String contents[] = path.list();
      System.out.println("List of files and directories in the specified directory:");
      for(int i=0; i < contents.length; i++) {
         System.out.println(contents[i]);
      }
   }
}

Output

List of files and directories in the specified directory:
SampleDirectory1
SampleDirectory2
SampleFile1.txt
SampleFile2.txt
SapmleFile3.txt

listFiles() method Example

import java.io.File;
import java.io.IOException;
public class ListOfFiles {
   public static void main(String args[]) throws IOException {
      //Creating a File object for directory
      File path = new File("D:\\ExampleDirectory");
      //List of all files and directories
      File files [] = path.listFiles();
      System.out.println("List of files and directories in the specified directory:");
      for(File file : files) {
         System.out.println("File name: "+file.getName());
         System.out.println("File path: "+file.getAbsolutePath());
         System.out.println(" ");
      }
   }
}

Output

List of files and directories in the specified directory:
File name: SampleDirectory1
File path: D:\ExampleDirectory\SampleDirectory1

File name: SampleDirectory2
File path: D:\ExampleDirectory\SampleDirectory2

File name: SampleFile1.txt
File path: D:\ExampleDirectory\SampleFile1.txt

File name: SampleFile2.txt
File path: D:\ExampleDirectory\SampleFile2.txt

File name: SapmleFile3.txt
File path: D:\ExampleDirectory\SapmleFile3.txt
raja
Published on 15-Oct-2019 08:06:13
Advertisements