Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to search / find files in a directory using DirectoryStream in Java 7.?

Given directory "D:\books\java" having 5 pdf files as shown below :




Program to demonstrate how to search / find files in a directory using DirectoryStream in Java 7.

package com.hubberspot.java7;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class SearchFilesInDirectory {

 public static void main(String[] args) {

  // 1. Create a path to the directory
  // where search for the files is to be done.
  Path dirPath = Paths.get("D:\\books\\java");

  DirectoryStream < Path > dirStream = null;

  try {
   // 2. Create a DirectoryStream instance using 
   // Files.newDirectoryStream(). The instance
   // is created by passing the Path of the directory
   // to be searched and the type of files as a filter
   // here we are using filter to search all pdf files
   // in the directory
   dirStream = Files.newDirectoryStream(dirPath, "*.pdf");

   // 3. Looping each file and printing the name
   // on the console
   for (Path entry : dirStream) {

    System.out.println(entry.getFileName());

   }
  } catch (IOException e) {

   System.out.println(e.getMessage());

  } finally {
   // 4. Closing the DirectoryStream
   try {

    dirStream.close();

   } catch (IOException e) {

    e.printStackTrace();
   }  
  }  
 }
}




Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot