How to list all files (only) from a directory using Java?

JavaServer Side ProgrammingProgramming

The ListFiles() method returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.

The File Filter interface is filter for the path names you can pass this as a parameter to the listFiles() method. This method filters the file names passed on the passed filter.

To get the files in a folder implement a FileFilter which accepts only files and pass it as a parameter to the listFiles() method.

Following is a screen shot of the contents of the ExampleDirectory

Example

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class Demo{
   public static void main(String args[]) throws IOException {
    //Creating a File object for directory
    File directoryPath = new File("D:\\ExampleDirectory");
    //Creating filter for directories files
    FileFilter fileFilter = new FileFilter(){
         public boolean accept(File dir) {          
            if (dir.isFile()) {
               return true;
            } else {
               return false;
            }
         }
      };        
      File[] list = directoryPath.listFiles(fileFilter);
      System.out.println("List of the jpeg files in the specified directory:");  
      for(File fileName : list) {
         System.out.println(fileName);
      }  
   }
}

Output

List of the jpeg files in the specified directory:
D:\ExampleDirectory\demo1.pdf
D:\ExampleDirectory\demo2.pdf
D:\ExampleDirectory\sample1.txt
D:\ExampleDirectory\sample2.txt
D:\ExampleDirectory\sample3.txt
D:\ExampleDirectory\sample_jpeg1.jpg
D:\ExampleDirectory\sample_jpeg2.jpg
D:\ExampleDirectory\test1.docx
D:\ExampleDirectory\test2.docx

Example

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ListOfFiles {
   public static void main(String[] args) throws IOException {
      Stream<Path> path = Files.walk(Paths.get("D:\\ExampleDirectory"));
      path = path.filter(Files::isRegularFile);
      path.forEach(System.out::println);
    }
}

Output

D:\ExampleDirectory\demo1.pdf
D:\ExampleDirectory\demo2.pdf
D:\ExampleDirectory\sample1.txt
D:\ExampleDirectory\sample2.txt
D:\ExampleDirectory\sample3.txt
D:\ExampleDirectory\sample_jpeg1.jpg
D:\ExampleDirectory\sample_jpeg2.jpg
D:\ExampleDirectory\test1.docx
D:\ExampleDirectory\test2.docx
raja
Published on 08-Feb-2021 15:41:01
Advertisements