- Program: How to get file list from a folder filtered by extensions?
- Java File IO Operations Sample Code Examples
- How to filter the files by file extensions and show the file names in Java?
- Example
- Output
- Filter file by extension java
- Constructor Summary
- Method Summary
- Methods declared in class java.lang.Object
- Constructor Detail
- FileNameExtensionFilter
- Method Detail
- accept
- getDescription
- getExtensions
- toString
- How to find files with the file extension in Java
- 1. Find files with a specified file extension
- 2. Find files with multiple file extensions
- How to filter the files by file extensions java
- Example:
- Output:
Program: How to get file list from a folder filtered by extensions?
Below example shows how to get list of all file objects from the given folder. First create File object by passing folder path. Call listFiles() method on file object to get list of file names in the given folder.
package com.java2novice.files; import java.io.File; import java.io.FilenameFilter; public class MyFilteredFileList < public static void main(String a[])< File file = new File("C:/MyFolder/"); File[] files = file.listFiles(new FilenameFilter() < @Override public boolean accept(File dir, String name) < if(name.toLowerCase().endsWith(".csv"))< return true; >else < return false; >> >); for(File f:files) < System.out.println(f.getName()); >> >
Java File IO Operations Sample Code Examples
- All file operations.
- Show list of all file names from a folder.
- How to get list of all files from a folder?
- Filter the files by file extensions and show the file names.
- How to read file content using byte array?
- How to read file content line by line in java?
- How to read property file in static context?
- How to read input from console in java?
- How to get file list from a folder filtered by extensions?
- How to get file URI reference?
- How to store and read objects from a file?
- How to create and store property file dynamically?
- How to store property file as xml file?
- How to get file last modified time?
- How to convert byte array to inputstream?
- How to convert inputstream to reader or BufferedReader?
- How to convert byte array to reader or BufferedReader?
- How to set file permissions in java?
- How to read a file using BufferedInputStream?
- How to create temporary file in java?
- How to write or store data into temporary file in java?
- How to delete temporary file in java?
- How to write string content to a file in java?
- How to write byte content to a file in java?
How to filter the files by file extensions and show the file names in Java?
The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
To get the list of all the existing files in a directory this class provides five different methods to get the details of all files in a particular folder −
- String[] list()
- File[] listFiles()
- String[] list(FilenameFilter filter)
- File[] listFiles(FilenameFilter filter)
- File[] listFiles(FileFilter filter)
Among these, the String[] list(FilenameFilter filter) method 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 get the file names based on extensions implement this interface as such and pass its object to the above specified list() method of the file class.
Example
Assume we have a folder named ExampleDirectory in the directory D with 7 files and 2 directories as −
The following Java program prints the names of the text files and jpeg files in the path D:\ExampleDirectory separately.
import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class ListOfFiles < public static void main(String args[]) throws IOException < //Creating a File object for directory File directoryPath = new File("D:\ExampleDirectory"); FilenameFilter textFilefilter = new FilenameFilter()< public boolean accept(File dir, String name) < String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".txt")) < return true; >else < return false; >> >; FilenameFilter jpgFilefilter = new FilenameFilter() < public boolean accept(File dir, String name) < String lowercaseName = name.toLowerCase(); if (lowercaseName.endsWith(".jpg")) < return true; >else < return false; >> >; //List of all the text files String textFilesList[] = directoryPath.list(textFilefilter); System.out.println("List of the text files in the specified directory:"); for(String fileName : textFilesList) < System.out.println(fileName); >String imageFilesList[] = directoryPath.list(jpgFilefilter); System.out.println("List of the jpeg files in the specified directory:"); for(String fileName : imageFilesList) < System.out.println(fileName); >> >
Output
List of the text files in the specified directory: SampleFile1.txt SampleFile2.txt SapmleFile3.txt List of the jpeg files in the specified directory: cassandra_logo.jpg cat.jpg coffeescript_logo.jpg javafx_logo.jpg
Filter file by extension java
An implementation of FileFilter that filters using a specified set of extensions. The extension for a file is the portion of the file name after the last «.». Files whose name does not contain a «.» have no file name extension. File name extension comparisons are case insensitive. The following example creates a FileNameExtensionFilter that will show jpg files:
FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg"); JFileChooser fileChooser = . ; fileChooser.addChoosableFileFilter(filter);
Constructor Summary
Method Summary
Methods declared in class java.lang.Object
Constructor Detail
FileNameExtensionFilter
public FileNameExtensionFilter(String description, String. extensions)
Creates a FileNameExtensionFilter with the specified description and file name extensions. The returned FileNameExtensionFilter will accept all directories and any file with a file name extension contained in extensions .
Method Detail
accept
Tests the specified file, returning true if the file is accepted, false otherwise. True is returned if the extension matches one of the file name extensions of this FileFilter , or the file is a directory.
getDescription
getExtensions
toString
Returns a string representation of the FileNameExtensionFilter . This method is intended to be used for debugging purposes, and the content and format of the returned string may vary between implementations.
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
How to find files with the file extension in Java
This article shows how to Java 8 Files.walk to walk a file tree and stream operation filter to find files that match a specific file extension from a folder and its subfolders.
// find files matched `png` file extension from folder C:\\test try (Stream walk = Files.walk(Paths.get("C:\\test"))) < result = walk .filter(p ->!Files.isDirectory(p)) // not a directory .map(p -> p.toString().toLowerCase()) // convert path to string .filter(f -> f.endsWith("png")) // check end with .collect(Collectors.toList()); // collect all matched to a List >
In the Files.walk method, the second argument, maxDepth defined the maximum number of directory levels to visit. And we can assign maxDepth = 1 to find files from the top-level folder only (exclude all its subfolders)
try (Stream walk = Files.walk(Paths.get("C:\\test"), 1)) < //. >
1. Find files with a specified file extension
This example finds files matched with png file extension. The finds start at the top-level folder C:\\test and included all levels of subfolders.
package com.mkyong.io.howto; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FindFileByExtension1 < public static void main(String[] args) < try < Listfiles = findFiles(Paths.get("C:\\test"), "png"); files.forEach(x -> System.out.println(x)); > catch (IOException e) < e.printStackTrace(); >> public static List findFiles(Path path, String fileExtension) throws IOException < if (!Files.isDirectory(path)) < throw new IllegalArgumentException("Path must be a directory!"); >List result; try (Stream walk = Files.walk(path)) < result = walk .filter(p ->!Files.isDirectory(p)) // this is a path, not string, // this only test if path end with a certain path //.filter(p -> p.endsWith(fileExtension)) // convert path to string first .map(p -> p.toString().toLowerCase()) .filter(f -> f.endsWith(fileExtension)) .collect(Collectors.toList()); > return result; > >
c:\test\bk\logo-new.png c:\test\bk\resize-default.png c:\test\google.png c:\test\test1\test2\java.png .
2. Find files with multiple file extensions
This example finds files matched with multiple file extensions ( .png , .jpg , .gif ).
package com.mkyong.io.howto; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FindFileByExtension2 < public static void main(String[] args) < try < String[] extensions = ; List files = findFiles(Paths.get("C:\\test"), extensions); files.forEach(x -> System.out.println(x)); > catch (IOException e) < e.printStackTrace(); >> public static List findFiles(Path path, String[] fileExtensions) throws IOException < if (!Files.isDirectory(path)) < throw new IllegalArgumentException("Path must be a directory!"); >List result; try (Stream walk = Files.walk(path, 1)) < result = walk .filter(p ->!Files.isDirectory(p)) // convert path to string .map(p -> p.toString().toLowerCase()) .filter(f -> isEndWith(f, fileExtensions)) .collect(Collectors.toList()); > return result; > private static boolean isEndWith(String file, String[] fileExtensions) < boolean result = false; for (String fileExtension : fileExtensions) < if (file.endsWith(fileExtension)) < result = true; break; >> return result; > >
c:\test\bk\logo-new.png c:\test\bk\resize-default.gif c:\test\bk\resize-fast.gif c:\test\bk\resize.png c:\test\google.jpg c:\test\google.png c:\test\test1\test2\java.png c:\test\test1\test2\java.jpg
2.2 The isEndWith() method can be shorter with Java 8 stream anyMatch .
private static boolean isEndWith(String file, String[] fileExtensions) < // Java 8, try this boolean result = Arrays.stream(fileExtensions).anyMatch(file::endsWith); return result; // old school style /*boolean result = false; for (String fileExtension : fileExtensions) < if (file.endsWith(fileExtension)) < result = true; break; >> return result;*/ >
2.3 We also can remove the isEndWith() method and puts the anyMatch into the filter directly.
public static List findFiles(Path path, String[] fileExtensions) throws IOException < if (!Files.isDirectory(path)) < throw new IllegalArgumentException("Path must be a directory!"); >List result; try (Stream walk = Files.walk(path, 1)) < result = walk .filter(p ->!Files.isDirectory(p)) // convert path to string .map(p -> p.toString().toLowerCase()) //.filter(f -> isEndWith(f, fileExtensions)) // lambda //.filter(f -> Arrays.stream(fileExtensions).anyMatch(ext -> f.endsWith(ext))) // method reference .filter(f -> Arrays.stream(fileExtensions).anyMatch(f::endsWith)) .collect(Collectors.toList()); > return result; >
2.4 We can further enhance the program by passing different conditions into the stream filter ; Now, the program can easily search or find files with a specified pattern from a folder. For examples:
Find files with filename starts with «abc».
List result; try (Stream walk = Files.walk(path)) < result = walk .filter(p ->!Files.isDirectory(p)) // convert path to string .map(p -> p.toString()) .filter(f -> f.startsWith("abc")) .collect(Collectors.toList()); >
Find files with filename containing the words «mkyong».
List result; try (Stream walk = Files.walk(path)) < result = walk .filter(p ->!Files.isDirectory(p)) // convert path to string .map(p -> p.toString()) .filter(f -> f.contains("mkyong")) .collect(Collectors.toList()); >
How to filter the files by file extensions java
We need to implement FilenameFilter class and override accept() method.
Example:
package com.w3spoint; import java.io.File; import java.io.FilenameFilter; public class FilesFilter { public static void main(String args[]){ File file = new File("D:/Test files/"); String[] files = file.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if(name.toLowerCase().endsWith(".txt")){ return true; } else { return false; } } }); for(String f:files){ System.out.println(f); } } }