How to find the file using Java?


Following example shows the way to look for a particular file in a directory by creating a File filter. Following example displays all the files having file names beginning with 'b'.

Example

Live Demo

import java.io.*;

public class Main {
   public static void main(String[] args) {
      File dir = new File("C:");
     
      FilenameFilter filter = new FilenameFilter() {
         public boolean accept (File dir, String name) {
            return name.startsWith("b");
         }
      };
      String[] children = dir.list(filter);

      if (children == null) {
         System.out.println("Either dir does not exist or is not a directory");
      } else {
         for (int i=0; i< children.length; i++) {
            String filename = children[i];
            System.out.println(filename);
        }
      }
   }
}

Output

build
build.xml

Swarali Sree
Swarali Sree

I love thought experiments.

Updated on: 30-Jul-2019

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements