- How to get extension of a File in Java
- 2. Get file extension using filter method from Java 8
- 3. Obtain file extension with Apache Commons IO library
- 4. Use Guava to get file extension
- 5. Conclusion
- 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
- Java Files.list
- Files.list current directory
- Files.list directories
- Files.list by file extensions
- Files.list count files
- Author
- List multiple image, video, text files (extensions) in directory/folder (FilenameFilter/java)
- 1. Program: list multiple files like image, video, text (FilenameFilter/java)
- 2. Input directory containing file formats like image, videos, text etc.
- 3. Output: list multiple image, video, text files (Java/FilenameFilter)
- You may also like:
- How to filter the files by file extensions and show the file names in Java?
- Example
- Output
How to get extension of a File in Java
In this tutorial, we are going to present several ways to get the extension of a File using plain Java and libraries such as Guava or Apache Commons IO.
To test different approaches and solutions we create an empty text file under the path: /tmp/test.txt .
2. Get file extension using filter method from Java 8
Let’s start with the first approach in plain Java:
package com.frontbackend.java.io.extension; import java.io.File; import java.util.Optional; public class GetFileExtensionUsingFilter < public static void main(String[] args) < File source = new File("/tmp/test.txt"); String filename = source.getName(); String extension = Optional.of(filename) .filter(f ->f.contains(".")) .map(f -> f.substring(filename.lastIndexOf(".") + 1)) .orElse(""); System.out.println(extension); > >
This solution first checks if a filename contains the dot . character. Then returns all characters after the last occurrence of the dot . .
This method will return an empty string if no extension found.
3. Obtain file extension with Apache Commons IO library
The Apache Commons IO library provides a special utility method to find filename extension. Let’s check the following solution:
package com.frontbackend.java.io.extension; import java.io.File; import org.apache.commons.io.FilenameUtils; public class GetFileExtensionUsingFilenameUtils < public static void main(String[] args) < File source = new File("/tmp/test.txt"); String filename = source.getName(); System.out.println(FilenameUtils.getExtension(filename)); // "txt" System.out.println(FilenameUtils.getExtension("test")); // "" >>
In this example, we used FilenameUtils.getExtension(. ) method that is the first step checks if given String is empty. Then with lastIndexOf(. ) function it finds the last occurrence of the dot character and returns all characters after that dot.
When filename does not contain any extension, FilenameUtils.getExtension(. ) will return an empty String.
4. Use Guava to get file extension
The last approach use Files utility class from Guava library:
package com.frontbackend.java.io.extension; import java.io.File; import com.google.common.io.Files; public class GetFileExtensionUsingFiles < public static void main(String[] args) < File source = new File("/tmp/test.txt"); String filename = source.getName(); System.out.println(Files.getFileExtension(filename)); // "txt" >>
This solution is very similar to Apache Commons IO . Files.getFileExtension(. ) method will do all necessary work for us and return the file extension or an empty string if the file does not have an extension.
5. Conclusion
In this short article, we presented various ways to obtain file extension in Java. All approaches based on filename and we can simply implement one using lastIndexOf and contains methods.
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()); >
Java Files.list
Java Files.list tutorial shows how to list files in Java with Files.list .
Files.list returns a lazily populated stream of directory elements. The listing is not recursive.
The elements of the stream are Path objects.
Files.list current directory
The first example lists the current directory.
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesListEx < public static void main(String[] args) throws IOException < Files.list(Paths.get(".")) .forEach(path ->System.out.println(path)); > >
The dot symbol represents the current working directory. We get the path object with Paths.get .
Files.list directories
The following example lists directories in the user’s home directory.
package com.zetcode; import java.io.File; import java.io.IOException; import java.nio.file.Files; public class FilesListEx2 < public static void main(String[] args) throws IOException < var homeDir = System.getProperty("user.home"); Files.list(new File(homeDir).toPath()) .filter(path ->path.toFile().isDirectory()) .forEach(System.out::println); > >
We convert the path object to a File with toFile and call the isDirectory method. The stream is filtered with filter .
Files.list by file extensions
The next program lists all PDF files.
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesListEx3 < public static void main(String[] args) throws IOException < var homeDir = System.getProperty("user.home") + System.getProperty("file.separator") + "Downloads"; Files.list(Paths.get(homeDir)).filter(path ->path.toString().endsWith(".pdf")) .forEach(System.out::println); > >
The program lists PDF files in the Downloads directory. The path object is converted to a string and we call endsWith on the string to check if it ends with pdf extension.
Files.list count files
We count the number of PDF files.
package com.zetcode; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class FilesListEx4 < public static void main(String[] args) throws IOException < var homeDir = System.getProperty("user.home") + System.getProperty("file.separator") + "Downloads"; var nOfPdfFiles = Files.list(Paths.get(homeDir)).filter(path ->path.toString() .endsWith(".pdf")).count(); System.out.printf("There are %d PDF files", nOfPdfFiles); > >
The number of files is determined with count .
In this article we have used Files.list to list the directory contents.
Author
My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.
List multiple image, video, text files (extensions) in directory/folder (FilenameFilter/java)
1. Program: list multiple files like image, video, text (FilenameFilter/java)
package org.learn; import java.io.File; import java.io.FilenameFilter; public class ListImgVidTxtFiles < public static void main(String[] args) < File directory = new File("d:/repo"); String[] videoFileFilters = ; String[] imageFileFilters = ; String[] txtFileFilters = ; System.out.println("1. Listing video files present in input directory"); printFiles(directory, videoFileFilters); System.out.println("\n2. Listing image files present in input directory"); printFiles(directory, imageFileFilters); System.out.println("\n3. Listing text files present in input directory"); printFiles(directory, txtFileFilters); > private static void printFiles(File inputDirectory, String[] filters) < File[] files = inputDirectory.listFiles(new FileFilter(filters)); for (File file : files) < System.out.println(file.getName()); >> > class FileFilter implements FilenameFilter < private String[] allowedExtensions = null; public FileFilter(String[] allowedExtensions) < this.allowedExtensions = allowedExtensions.clone(); >@Override public boolean accept(File dir, String name) < String fileExt = name.substring(name.lastIndexOf(".") + 1); for (String imgExt : allowedExtensions) < if (imgExt.compareToIgnoreCase(fileExt) == 0) return true; >return false; > >
2. Input directory containing file formats like image, videos, text etc.
Fig 1: Directory containing different files
3. Output: list multiple image, video, text files (Java/FilenameFilter)
1. Listing video files present in input directory Citizen Kane.wmv Pulp Fiction.mov The Dark Knight.avi 2. Listing image files present in input directory Harley.tif Royal.png Title.jpg Tulips.jpg 3. Listing text files present in input directory applicationLogs.txt sampleFile.txt
You may also like:
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