- How to search a file in a directory in java
- Example
- Output
- Example
- Finding Files
- Recursive Pattern Matching
- Java how to find files in directory java
- Find files in a folder using Java
- Java how to: Directory Searching
- Java Program to Search for a File in a Directory
- Java
- Java
- Java — Search for files in a directory
- Java Examples — Search a file in a directory
- Problem Description
- Solution
- Result
How to search a file in a directory in java
The List() method of the File class returns a String array containing the names of all the files and directories in the path represented by the current (File) object.
In order to search for a file you need to compare the name of each file in the directory to the name of the required file using the equals() method.
Example
import java.io.File; import java.util.Arrays; import java.util.Scanner; public class Example < public static void main(String[] argv) throws Exception < System.out.println("Enter the directory path: "); Scanner sc = new Scanner(System.in); String pathStr = sc.next(); System.out.println("Enter the desired file name: "); String file = sc.next(); System.out.println(file); File dir = new File(pathStr); String[] list = dir.list(); System.out.println(Arrays.toString(list)); boolean flag = false; for (int i = 0; i < list.length; i++) < if(file.equals(list[i]))< flag = true; >> if(flag)< System.out.println("File Found"); >else < System.out.println("File Not Found"); >> >
Output
Enter the directory path: D:\ExampleDirectory Enter the desired file name: demo2.pdf demo2.pdf [demo1.pdf, demo2.pdf, sample directory1, sample directory2, sample directory3, sample directory4, sample_jpeg1.jpg, sample_jpeg2.jpg, test1.docx, test2.docx] File Found
The String[] list(FilenameFilter filter) method of a File class returns a String array containing the names of all the files and directories in the path represented by the current (File) object. But the retuned array contains the filenames which are filtered based on the specified filter. The FilenameFilter is an interface in Java with a single method.
accept(File dir, String name)
To search for a file name you need to implement a FilenameFilter that matches the name of the desired file.
Example
import java.io.File; import java.io.FilenameFilter; public class Example < public static void main(String[] argv) throws Exception < File dir = new File("D:\ExampleDirectory"); FilenameFilter filter = new FilenameFilter() < public boolean accept(File dir, String name) < return name.equalsIgnoreCase("demo1.pdf"); >>; String[] files = dir.list(filter); if (files == null) < System.out.println("File Not Found"); >else < System.out.println("File Found"); >> >
Finding Files
If you have ever used a shell script, you have most likely used pattern matching to locate files. In fact, you have probably used it extensively. If you haven’t used it, pattern matching uses special characters to create a pattern and then file names can be compared against that pattern. For example, in most shell scripts, the asterisk, * , matches any number of characters. For example, the following command lists all the files in the current directory that end in .html :
The java.nio.file package provides programmatic support for this useful feature. Each file system implementation provides a PathMatcher . You can retrieve a file system’s PathMatcher by using the getPathMatcher(String) method in the FileSystem class. The following code snippet fetches the path matcher for the default file system:
String pattern = . ; PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
The string argument passed to getPathMatcher specifies the syntax flavor and the pattern to be matched. This example specifies glob syntax. If you are unfamiliar with glob syntax, see What is a Glob.
Glob syntax is easy to use and flexible but, if you prefer, you can also use regular expressions, or regex, syntax. For further information about regex, see the Regular Expressions lesson. Some file system implementations might support other syntaxes.
If you want to use some other form of string-based pattern matching, you can create your own PathMatcher class. The examples in this page use glob syntax.
Once you have created your PathMatcher instance, you are ready to match files against it. The PathMatcher interface has a single method, matches , that takes a Path argument and returns a boolean: It either matches the pattern, or it does not. The following code snippet looks for files that end in .java or .class and prints those files to standard output:
PathMatcher matcher = FileSystems.getDefault().getPathMatcher(«glob:*.»); Path filename = . ; if (matcher.matches(filename))
Recursive Pattern Matching
Searching for files that match a particular pattern goes hand-in-hand with walking a file tree. How many times do you know a file is somewhere on the file system, but where? Or perhaps you need to find all files in a file tree that have a particular file extension.
The Find example does precisely that. Find is similar to the UNIX find utility, but has pared down functionally. You can extend this example to include other functionality. For example, the find utility supports the -prune flag to exclude an entire subtree from the search. You could implement that functionality by returning SKIP_SUBTREE in the preVisitDirectory method. To implement the -L option, which follows symbolic links, you could use the four-argument walkFileTree method and pass in the FOLLOW_LINKS enum (but make sure that you test for circular links in the visitFile method).
To run the Find application, use the following format:
The pattern is placed inside quotation marks so any wildcards are not interpreted by the shell. For example:
Here is the source code for the Find example:
/** * Sample code that finds files that match the specified glob pattern. * For more information on what constitutes a glob pattern, see * https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob * * The file or directories that match the pattern are printed to * standard out. The number of matches is also printed. * * When executing this application, you must put the glob pattern * in quotes, so the shell will not expand any wild cards: * java Find . -name "*.java" */ import java.io.*; import java.nio.file.*; import java.nio.file.attribute.*; import static java.nio.file.FileVisitResult.*; import static java.nio.file.FileVisitOption.*; import java.util.*; public class Find < public static class Finder extends SimpleFileVisitor < private final PathMatcher matcher; private int numMatches = 0; Finder(String pattern) < matcher = FileSystems.getDefault() .getPathMatcher("glob:" + pattern); >// Compares the glob pattern against // the file or directory name. void find(Path file) < Path name = file.getFileName(); if (name != null && matcher.matches(name)) < numMatches++; System.out.println(file); >> // Prints the total number of // matches to standard out. void done() < System.out.println("Matched: " + numMatches); >// Invoke the pattern matching // method on each file. @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) < find(file); return CONTINUE; >// Invoke the pattern matching // method on each directory. @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) < find(dir); return CONTINUE; >@Override public FileVisitResult visitFileFailed(Path file, IOException exc) < System.err.println(exc); return CONTINUE; >> static void usage() < System.err.println("java Find " + " -name \"\""); System.exit(-1); > public static void main(String[] args) throws IOException < if (args.length < 3 || !args[1].equals("-name")) usage(); Path startingDir = Paths.get(args[0]); String pattern = args[2]; Finder finder = new Finder(pattern); Files.walkFileTree(startingDir, finder); finder.done(); >>
Recursively walking a file tree is covered in Walking the File Tree.
Java how to find files in directory java
Following example displays all the files having file names starting with ‘b’. Java Output Second Approach The list() method is called on the dir object of the File class and the list of files in the ‘flist’ array.
Find files in a folder using Java
What you want is File.listFiles(FileNameFilter filter) .
That will give you a list of the files in the directory you want that match a certain filter.
The code will look similar to:
// your directory File f = new File("C:\\example"); File[] matchingFiles = f.listFiles(new FilenameFilter() < public boolean accept(File dir, String name) < return name.startsWith("temp") && name.endsWith("txt"); >>);
You can use a FilenameFilter, like so:
File dir = new File(directory); File[] matches = dir.listFiles(new FilenameFilter() < public boolean accept(File dir, String name) < return name.startsWith("temp") && name.endsWith(".txt"); >>);
I know, this is an old question. But just for the sake of completeness, the lambda version.
File dir = new File(directory); File[] files = dir.listFiles((dir1, name) -> name.startsWith("temp") && name.endsWith(".txt"));
Listing files in a directory matching a pattern in Java, 6 Answers 6 ; 147 · See File#listFiles(FilenameFilter). File ; 74 · Since Java 8 you can use lambdas and achieve shorter code: File ; 27 · Since java
Java how to: Directory Searching
In this video I show you how to list files within a user specified directory, and how to sort those Duration: 8:21
Java Program to Search for a File in a Directory
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.File.list() method. This method is very useful when we want to find files with a specific extension within a folder.
First Approach
- Create a class MyFilenameFilter which implements the FilenameFilter interface and overrides the accept() method of FilenameFilter interface.
- The accept() method takes two arguments of which the first one is the directory name and the second one is the filename.
- 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.
- The directory object of File class is initiated with the director name and the filter object of MyFilenameFilter class is initiated with the initials provided by the user.
- The list() method is invoked on the dir object which returns an array of files that satisfy the condition.
- The array is iterated over and the name of the required files are printed to the output screen.
Code Implementation
Java
Second Approach
- 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.
This method is a bit different from the previous one as the user needs to specify the exact name of the file in this case.
Code Implementation
Java
Java how to: Directory Searching, In this video I show you how to list files within a user specified directory, and how to sort those Duration: 8:21
Java — Search for files in a directory
you can try something like this:
import java.io.*; import java.util.*; class FindFile < public void findFile(String name,File file) < File[] list = file.listFiles(); if(list!=null) for (File fil : list) < if (fil.isDirectory()) < findFile(name,fil); >else if (name.equalsIgnoreCase(fil.getName())) < System.out.println(fil.getParentFile()); >> > public static void main(String[] args) < FindFile ff = new FindFile(); Scanner scan = new Scanner(System.in); System.out.println("Enter the file to be searched.. " ); String name = scan.next(); System.out.println("Enter the directory where to search "); String directory = scan.next(); ff.findFile(name,new File(directory)); >>
J:\Java\misc\load>java FindFile Enter the file to be searched.. FindFile.java Enter the directory where to search j:\java\ FindFile.java Found in->j:\java\misc\load
Using Java 8+ features we can write the code in few lines:
protected static Collection find(String fileName, String searchDirectory) throws IOException < try (Streamfiles = Files.walk(Paths.get(searchDirectory))) < return files .filter(f ->f.getFileName().toString().equals(fileName)) .collect(Collectors.toList()); > >
Files.walk returns a Stream which is «walking the file tree rooted at» the given searchDirectory . To select the desired files only a filter is applied on the Stream files . It compares the file name of a Path with the given fileName .
Note that the documentation of Files.walk requires
This method must be used within a try-with-resources statement or similar control structure to ensure that the stream’s open directories are closed promptly after the stream’s operations have completed.
I’m using the try-resource-statement.
For advanced searches an alternative is to use a PathMatcher :
protected static Collection find(String searchDirectory, PathMatcher matcher) throws IOException < try (Streamfiles = Files.walk(Paths.get(searchDirectory))) < return files .filter(matcher::matches) .collect(Collectors.toList()); >>
An example how to use it to find a certain file:
public static void main(String[] args) throws IOException < String searchDirectory = args[0]; String fileName = args[1]; PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:.*" + fileName); Collectionfind = find(searchDirectory, matcher); System.out.println(find); >
More about it: Oracle Finding Files tutorial
With **Java 8* there is an alternative that use streams and lambdas:
public static void recursiveFind(Path path, Consumer c) < try (DirectoryStreamnewDirectoryStream = 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:
How to read all files in a folder from Java?, List
Java Examples — Search a file in a directory
Problem Description
How to search for a file in a directory ?
Solution
Following example shows how to search for a particular file in a directory by making a Filefiter. Following example displays all the files having file names starting with ‘b’.
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); >> > >
Result
The above code sample will produce the following result.
Java Examples — Searching Files, 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. import java.io.