Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Search for files in a directory

This is supposed to be simple, but I can't get it - "Write a program that searches for a particular file name in a given directory." I've found a few examples of a hardcoded filename and directory, but I need both the dir and file name to be as entered by the user.

public static void main(String[] args) {
    String fileName = args[0]; // For the filename declaration
    String directory;     
    boolean found;

    File dir = new File(directory);

    File[] matchingFiles = dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String fileName) {
            return true;
        }
    });

}
like image 864
A C Avatar asked Mar 25 '13 20:03

A C


People also ask

How to search for files in a directory in Java?

Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java. io.

How to search for a file in windows using Java?

You can use the the FileVisitor in Java and then Files. walkFileTree(startDir, visitor) to walk the filetree recursively from a starting dir. which is called for every File. In this method you can check if it is the file you are searching for.

How do I search for a file in Java?

From the Window's Start button, select "Search". Select "All files and folders" on the left. In the pop-up window, type in the file name (with . java properly) in "All or part of the file name".

What does the files list () method in Java do?

list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.

How to search all files inside a directory in Java?

How to search all files inside a directory ? Following example demonstrares how to search and get a list of all files under a specified directory by using dir.list () method of File class. The above code sample will produce the following result. The following is an another sample example of search all files inside a directory in Java

How to search for files in Java using filenamefilter?

Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files.

How to check if an empty directory or directory does not exist?

"Empty directory or directory does not exists."); The list () method is called on the dir object of the File class and the list of files in the ‘flist’ array. Each file in the ‘flist’ array is checked against the required filename. If a match is found it is printed on the screen.

How do I search for a file that starts with initials?

The accept () method returns true if the filename starts with the specified initials else returns false. The class FindFile contains the main method which accepts the user input like the desired directory to search and the initials of the file to search.


1 Answers

With **Java 8* there is an alternative that use streams and lambdas:

public static void recursiveFind(Path path, Consumer<Path> c) {
  try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path)) {
    StreamSupport.stream(newDirectoryStream.spliterator(), false)
                 .peek(p -> {
                   c.accept(p);
                   if (p.toFile()
                        .isDirectory()) {
                     recursiveFind(p, c);
                   }
                 })
                 .collect(Collectors.toList());
  } catch (IOException e) {
    e.printStackTrace();
  }
}

So this will print all the files recursively:

recursiveFind(Paths.get("."), System.out::println);

And this will search for a file:

recursiveFind(Paths.get("."), p -> { 
  if (p.toFile().getName().toString().equals("src")) {
    System.out.println(p);
  }
});
like image 157
freedev Avatar answered Sep 19 '22 13:09

freedev