Java find files filter

Java File listFiles(FileFilter filter) method with examples

The listFiles(FileFilter filter) method returns an array of File objects that represent the files and directories that satisfy specified FileFilter .

2. Method signature

public File[] listFiles(FileFilter filter) 

Parameters:

Returns

  • File [] — an array of File objects that represent files and directories that satisfy the specified filter.

Throws

3. Examples

3.1. Code snippet that prints only files (!file.isDirectory()) with the .txt extension (file.getName().endsWith(«.txt»))

package com.frontbackend.java.io; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.util.Arrays; public class FrontBackend < public static void main(String args[]) < try < File tmp = new File("/tmp/ttt"); FileFilter fileFilter = file ->!file.isDirectory() && file.getName() .endsWith(".txt"); File[] list = tmp.listFiles(fileFilter); if (list != null) < Arrays.stream(list) .forEach(file ->< System.out.println(file.getPath() + " " + (file.isDirectory() ? "dir" : "file")); >); > > catch (Exception e) < e.printStackTrace(); >> > 
/tmp/ttt/dest.txt file /tmp/ttt/test.txt file 

4. Conclusion

In this article, we presented the listFiles(FileFilter filter) method that could be used to filter files and directories from the specified path in the filesystem using FileFilter object.

Источник

Java FilenameFilter to Find Files Matching Pattern

Many times we need to traverse and find all files with a certain name pattern to do some operations on those files, for example deleting those files. This is more often required when we want to delete all .log or .tmp files from the server after a certain time using the application (if such a requirement exists).

Читайте также:  Html img не показывает

In Java, we can use FilenameFilter class. It tests if a specified file should be included in a file list. To use FilenameFilter, override the accept(dir, name) method that contains the logic to check if the file has to be included in the filtered list.

From Java 8 onwards, FileNameFilter is a functional interface. The classes that implement this interface are used to filter filenames. It has a single method accept() that takes two parameters:

The given LogFilterFilter class can be used to filter all log files from a list of files.

public class LogFilterFilter implements FilenameFilter < @Override public boolean accept(File dir, String fileName) < return fileName.endsWith(".log"); >>

2. How to use FilenameFilter

The best way to use the FileNameFilter is to pass it to one of the following methods in java.io.File class where File represents a directory location:

  • String[] list(filter) : returns an array of strings naming the files and directories in the target directory.
  • File[] listFiles(filter) : returns an array of files and directories in the target directory.

3. FilenameFilter Examples

Let us look at a few examples to understand how we can use the FilenameFilter class.

Example 1: Java program to use FilenameFilter to find all log files

In this example, we will use FilenameFilter instance to list out all «.log» files in folder «c:/temp» . We will also delete all these log files.

String targetDirectory = "c:\\temp"; File dir = new File(targetDirectory); //Find out all log files String[] logFiles = dir.list(new LogFilterFilter()); //If no log file found; no need to go further if (logFiles.length == 0) return; //This code will delete all log files one by one for (String fileName : logFiles)

Example 2: Creating FilenameFilter using Lambda Expression

Since FileNameFilter is a functional interface, we can reduce and create it using a lambda expression.

FilenameFilter logFileFilter = (d, s) -> < return s.toLowerCase().endsWith(".log"); >; String[] logFiles = dir.list(logFileFilter);

Example 3: Creating FilenameFilter containing Regular Expressions

This Java program filters all files based on file names matching a regular expression. For example, we want to list all the files that do not contain a number in their names.

FilenameFilter filter = (d, s) -> < return s.matches("[a-zA-z]+\\.[a-z]+"); >; String[] filteredFiles = dir.list(filter);

In this Java tutorial, we learned to use the FilenameFilter to traverse a directory and search all files with names matching a specified pattern.

Источник

Java FileFilter (with Examples)

Java FileFilter is a filter for File objects denoting the files and subdirectories in a given directory. It is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

The use of FileFilter is similar to FilenameFilter except the latter uses only the name of the file to make the decision. The FileFilter accepts File objects and thus can be used to filter the files based on other attributes such as read-only.

The FileFilter class has only a single method accept() that tests whether or not the specified abstract pathname should be included in a pathname list.

It returns true if and only if pathname should be included in the list.

FileFilter logFilefilter = new FileFilter() < public boolean accept(File file) < if (file.getName().endsWith(".log")) < return true; >return false; > >;

The best way to use the FileFilter is to pass it to listFiles() method in File class where File represents a directory location.

File directory = new File("/path/directory"); File[] files = directory.listFiles(logFilefilter);

3.1. Filtering all matching files in the specified directory

In the given Java example, we are finding all the log files from the «c:/temp» directory.

File directory = new File("c:/temp"); //Verify if it is a valid directory if (!(directory.exists() && directory.isDirectory())) < System.out.println(String.format("Directory %s does not exist", directory)); return; >FileFilter logFilefilter = new FileFilter() < public boolean accept(File file) < if (file.getName().endsWith(".log")) < return true; >return false; > >; File[] files = directory.listFiles(logFilefilter); for (File f: files)

The above program will list down all .log files present in c:/temp folder.

3.2. Creating FileFilter with Lambda Expression

The given program uses the lambda expression syntax to create the FileFilter instance. Rest all the operations will be the same.

FileFilter logFileFilter = (file) -> < return file.getName().endsWith(".log"); >; File[] files = directory.listFiles(logFilefilter); 

Источник

In Java How to get list of files and search a file providing folder path? FilenameFilter Interface Example

In this tutorial we will go over FilenameFilter interface to search a file and list of files with given file extension (i.e. .png, .jpg, .jpeg, .txt, .pdf).

lifeFiles returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

The behavior of this method is the same as that of the listFiles() method, except that the pathnames in the returned array must satisfy the filter.

If the given filter is null then all pathnames are accepted. Otherwise, a pathname satisfies the filter if and only if the value true results when the FilenameFilter.accept (File, String) method of the filter is invoked on this abstract pathname and the name of a file or directory in the directory that it denotes.

Some time back we have published a similar tutorial on how to search a file using java.nio.file package. Take a look at that too when you get a chance. java.nio.file defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems.

Let’s get started:

Create CrunchifyFileSearchUsingFilenameFilter.java

package crunchify.com.tutorial; import java.io.File; import java.io.FilenameFilter; /** * @author Crunchify.com * In Java How to get list of files and search a file providing folder path? * FilenameFilter Interface Example */ public class CrunchifyFileSearchUsingFilenameFilter < public static void main(String[] args) < String crunchifyDirectory = "/Users/app/Download"; String crunchifyExt = ".txt"; crunchifySearchFilesWithExtension(crunchifyDirectory, crunchifyExt); >// FileNameFilter: Instances of classes that implement this interface are used to filter filenames. // These instances are used to filter directory listings in the list method of class File, and by the Abstract Window // Toolkit's file dialog component. public static class crunchifyFileNameFiler implements FilenameFilter < private final String crunchifyExt; public crunchifyFileNameFiler(String crunchifyExt) < // toLoverCase() Converts all of the characters in this String to lower case using the rules of the default locale. // This is equivalent to calling toLowerCase(Locale.getDefault()). this.crunchifyExt = crunchifyExt.toLowerCase(); >@Override public boolean accept(File crunchifyDirectory, String crunchifyName) < // endsWith(): Tests if this string ends with the specified suffix. return crunchifyName.toLowerCase().endsWith(crunchifyExt); >> private static void crunchifySearchFilesWithExtension(String crunchifyDirectory, String crunchifyExt) < // File class - Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname. File crunchifyFiles = new File(crunchifyDirectory); // exists(): Tests whether the file or directory denoted by this abstract pathname exists. if (!crunchifyFiles.exists()) crunchifyPrint(crunchifyDirectory + " Hmm.. Wrong Directory. Directory doesn't exists. " + crunchifyDirectory); // lifeFiles: Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is the same as that of the crunchifyListOfFiles() method, except that the pathnames in the returned array must satisfy the filter. // If the given filter is null then all pathnames are accepted. Otherwise, a pathname satisfies the filter if and only if the value true results when the FilenameFilter.accept(File, String) method of the filter is invoked on this abstract pathname and the name of a file or directory in the directory that it denotes. File[] crunchifyListOfFiles = crunchifyFiles.listFiles(new crunchifyFileNameFiler(crunchifyExt)); assert crunchifyListOfFiles != null; int crunchifyCounter = 0; if (crunchifyListOfFiles.length == 0) < crunchifyPrint(crunchifyDirectory + "Hmm.. Sorry. No file exist with given file extension: " + crunchifyExt); >else < for (File crunchifyFile : crunchifyListOfFiles) < crunchifyCounter++; // separator: The system-dependent default name-separator character, represented as a string for convenience. // This string contains a single character, namely separatorChar. crunchifyPrint("File # " + crunchifyCounter + ": " + crunchifyDirectory + File.separator + crunchifyFile.getName()); >> > // Simple Print Utility private static void crunchifyPrint(String print) < System.out.println(print); >>

Just run above program as a Java Application.

IntelliJ IDEA console result:

File # 1: /Users/app/Download/task.txt File # 2: /Users/app/Download/robots_files_copy.txt File # 3: /Users/app/Download/robots_nio.txt File # 4: /Users/app/Download/robots_httpcomponents.txt File # 5: /Users/app/Download/robots.txt File # 6: /Users/app/Download/robots_commons_io.txt File # 7: /Users/app/Download/robots_stream.txt File # 8: /Users/app/Download/docs-cpt-crunchify.txt Process finished with exit code 0

Let me know if you face any issue running above Java Program.

Option-2) as mentioned above search file using java.nio.file package.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion. 👋

Suggested Articles.

Источник

Listing All Files in a Directory in Java

Learn to use various Java APIs such as Files.list() and DirectoryStream to list all files present in a directory, including hidden files, recursively.

  • For using external iteration (for loop) use DirectoryStream .
  • For using Stream API operations, use Files.list() instead.

1. Listing Files Only in a Given Directory

1.1. Sream of Files with Files.list()

If we are interested in non-recursively listing the files and excluding all sub-directories and files in sub-directories, then we can use this approach.

  • Read all files and directories entries using Files.list().
  • Check if a given entry is a file using PredicateFile::isFile.
  • Collect all filtered entries into a List.
//The source directory String directory = "C:/temp"; // Reading only files in the directory try < Listfiles = Files.list(Paths.get(directory)) .map(Path::toFile) .filter(File::isFile) .collect(Collectors.toList()); files.forEach(System.out::println); > catch (IOException e)

1.2. DirectoryStream to Loop through Files

DirectoryStream is part of Java 7 and is used to iterate over the entries in a directory in for-each loop style.

Closing a directory stream releases any resources associated with the stream. Failure to close the stream may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that the stream is closed.

List fileList = new ArrayList<>(); try (DirectoryStream stream = Files .newDirectoryStream(Paths.get(directory))) < for (Path path : stream) < if (!Files.isDirectory(path)) < fileList.add(path.toFile()); >> > fileList.forEach(System.out::println);

2. Listing All Files in Given Directory and Sub-directories

2.1. Files.walk() for Stream of Paths

The walk() method returns a Stream by walking the file tree beginning with a given starting file/directory in a depth-first manner.

Note that this method visits all levels of the file tree.

String directory = "C:/temp"; List pathList = new ArrayList<>(); try (Stream stream = Files.walk(Paths.get(directory))) < pathList = stream.map(Path::normalize) .filter(Files::isRegularFile) .collect(Collectors.toList()); >pathList.forEach(System.out::println);

If you wish to include the list of Path instances for directories as well, then remove the filter condition Files::isRegularFile.

We can also write the file tree walking logic using the recursion. It gives a little more flexibility if we want to perform some intermediate steps/checks before adding the entry to list of the files.

String directory = "C:/temp"; //Recursively list all files List fileList = listFiles(directory); fileList.forEach(System.out::println); private static List listFiles(final String directory) < if (directory == null) < return Collections.EMPTY_LIST; >List fileList = new ArrayList<>(); File[] files = new File(directory).listFiles(); for (File element : files) < if (element.isDirectory()) < fileList.addAll(listFiles(element.getPath())); >else < fileList.add(element); >> return fileList; >

Please note that if we’re working with a large directory, then using DirectoryStream performs better.

3. Listing All Files of a Certain Extention

To get the list of all files of certain extensions only, use two predicates Files::isRegularFile and filename.endsWith(«.extension») together.

In given example, we are listing all .java files in a given directory and all of its sub-directories.

String directory = "C:/temp"; //Recursively list all files List pathList = new ArrayList<>(); try (Stream stream = Files.walk(Paths.get(directory))) < // Do something with the stream. pathList = stream.map(Path::normalize) .filter(Files::isRegularFile) .filter(path ->path.getFileName().toString().endsWith(".java")) .collect(Collectors.toList()); > pathList.forEach(System.out::println); >

4. Listing All Hidden Files

To find all the hidden files, we can use filter expression file -> file.isHidden() in any of the above examples.

List files = Files.list(Paths.get(dirLocation)) .filter(path -> path.toFile().isHidden()) .map(Path::toFile) .collect(Collectors.toList());

In the above examples, we learn to use the java 8 APIs loop through the files in a directory recursively using various search methods. Feel free to modify the code and play with it.

Источник

Оцените статью