- Java – Find files with given extension
- Program: Searching all files with “.png” extension
- Top Related Articles:
- About the Author
- 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
- Java Program to Get the File Extension
- Example 1: Java Program to get the file extension
- Example 2: Get the file extension of all files present in a directory
- Get the File Extension of a File in Java
- Get the File Extension Using the getExtension() Method in Java
- Get the File Extension of a File With the lastIndexOf() Method in Java
- Get the File Extension of a File With String Parsing in Java
- Get the File Extension of a File Using the replaceAll() Method in Java
- Get the File Extension of a File Using contains() and lastIndexOf() Method in Java
- Get the File Extension of a File Using ternary operators in Java
- Get the File Extension of a File Using stream() Method in Java
- Get the File Extension of a File Using Regex in Java
- Related Article — Java IO
- Related Article — Java File
- Write a java program to find File Extension.
- Input and Output Format
- Refer sample output for formatting specifications
- Program to Find File Extension in Java
- Output
- Get File Extension using Library
- Program to get extension file in Java using Apache Common IO
- Output
- Extract File Extension using Guava Library
- Program to get the File Extension in Java
- Output
Java – Find files with given extension
In this tutorial, we will see how to find all the files with certain extensions in the specified directory.
Program: Searching all files with “.png” extension
In this program, we are searching all “.png” files in the “Documents” directory(folder). I have placed three files Image1.png, Image2.png, Image3.png in the Documents directory.
Similarly, we can search files with the other extensions like “.jpeg”,”jpg”,”.xml”,”.txt” etc.
package com.beginnersbook; import java.io.*; public class FindFilesWithThisExtn < //specify the path (folder) where you want to search files private static final String fileLocation = "/Users/chaitanyasingh/Documents"; //extension you want to search for e.g. .png, .jpeg, .xml etc private static final String searchThisExtn = ".png"; public static void main(String args[]) < FindFilesWithThisExtn obj = new FindFilesWithThisExtn(); obj.listFiles(fileLocation, searchThisExtn); >public void listFiles(String loc, String extn) < SearchFiles files = new SearchFiles(extn); File folder = new File(loc); if(folder.isDirectory()==false)< System.out.println("Folder does not exists: " + fileLocation); return; >String[] list = folder.list(files); if (list.length == 0) < System.out.println("There are no files with " + extn + " Extension"); return; >for (String file : list) < String temp = new StringBuffer(fileLocation).append(File.separator) .append(file).toString(); System.out.println("file : " + temp); >> public class SearchFiles implements FilenameFilter < private String ext; public SearchFiles(String ext) < this.ext = ext; >@Override public boolean accept(File loc, String name) < if(name.lastIndexOf('.')>0) < // get last index for '.' int lastIndex = name.lastIndexOf('.'); // get extension String str = name.substring(lastIndex); // matching extension if(str.equalsIgnoreCase(ext)) < return true; >> return false; > > >
file : /Users/chaitanyasingh/Documents/Image1.png file : /Users/chaitanyasingh/Documents/Image2.png file : /Users/chaitanyasingh/Documents/Image3.png
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
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.
Java Program to Get the File Extension
To understand this example, you should have the knowledge of the following Java programming topics:
Example 1: Java Program to get the file extension
import java.io.File; class Main < public static void main(String[] args) < File file = new File("Test.java"); // convert the file name into string String fileName = file.toString(); int index = fileName.lastIndexOf('.'); if(index >0) < String extension = fileName.substring(index + 1); System.out.println("File extension is " + extension); >> >
- file.toString() — Converts the File object into a string.
- fileName.lastIndexOf(‘.’) — Returns the last occurrence of character. Since all file extension starts with ‘.’, we use the character ‘.’.
- fileName.substring() — Returns the string after character ‘.’.
Example 2: Get the file extension of all files present in a directory
Now, suppose we want to get the file extension of all the files present in a directory. We can use the above process in the loop.
import java.io.File; class Main < public static void main(String[] args) < File directory = new File("Directory"); // list all files present in the directory File[] files = directory.listFiles(); System.out.println("Files\t\t\tExtension"); for(File file : files) < // convert the file name into string String fileName = file.toString(); int index = fileName.lastIndexOf('.'); if(index >0) < String extension = fileName.substring(index + 1); System.out.println(fileName + "\t" + extension); >> > >
Files Extension Directory\file1.txt txt Directory\file2.svg svg Directory\file3.java java Directory\file4.py py Directory\file5.html html
Note: The output of the program depends on the directory you use and the files in the directory.
- If you are using the Gauva Library, you can directly use the getFileExtension() method to get the file extension. For example,
String fileName = "Test.java"; String extension = Files.getFileExtension(fileName);
String extension = FilenameUtils.getExtension("file.py") // returns py
Get the File Extension of a File in Java
- Get the File Extension Using the getExtension() Method in Java
- Get the File Extension of a File With the lastIndexOf() Method in Java
- Get the File Extension of a File With String Parsing in Java
- Get the File Extension of a File Using the replaceAll() Method in Java
- Get the File Extension of a File Using contains() and lastIndexOf() Method in Java
- Get the File Extension of a File Using ternary operators in Java
- Get the File Extension of a File Using stream() Method in Java
- Get the File Extension of a File Using Regex in Java
This tutorial introduces how to get the file extension of a file in Java.
Get the File Extension Using the getExtension() Method in Java
To get an extension of a file, we can use the getExtension() method of the FilenameUtils class. This method returns the extension of the file. Since this method belongs to Apache commons library, you must download the library from Apache official site to use JARs in your project.
import org.apache.commons.io.FilenameUtils; public class SimpleTesting public static void main(String[] args) String fileName = "student-records.pdf"; String fe = FilenameUtils.getExtension(fileName); System.out.println("File extension is : "+fe); > >
Get the File Extension of a File With the lastIndexOf() Method in Java
If you don’t want to use any built-in method then use the given code example that uses lastIndexOf() method to get the file extension. It is the simplest and easy way that involves only string methods. See the example below.
public class SimpleTesting public static void main(String[] args) String fileName = "student-records.pdf"; String fe = ""; int i = fileName.lastIndexOf('.'); if (i > 0) fe = fileName.substring(i+1); > System.out.println("File extension is : "+fe); > >
Get the File Extension of a File With String Parsing in Java
This is another solution that includes several scenarios including the one (if dot(.) is in the file path). This method returns the accurate result even if the file path has a dot(.) in between the file path. See the example below.
public class SimpleTesting public static void main(String[] args) String fileName = "folder\s.gr\fg\student-records.pdf"; String fe = ""; char ch; int len; if(fileName==null || (len = fileName.length())==0 || (ch = fileName.charAt(len-1))=='/' || ch=='\\' ||ch=='.' ) fe = ""; > int dotInd = fileName.lastIndexOf('.'), sepInd = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\')); if( dotInd sepInd ) fe = ""; > else fe = fileName.substring(dotInd+1).toLowerCase(); > System.out.println("File extension is : "+fe); > >
Get the File Extension of a File Using the replaceAll() Method in Java
We can use replaceAll() method to get file extension as we did in the below example. We use regular expression in this method and collect the result into a variable.
public class SimpleTesting public static void main(String[] args) String fileName = "folder\s.gr\fg\student-records.pdf"; String fe = ""; fe = fileName.replaceAll("^.*\\.(.*)$", "$1"); System.out.println("File extension is : "+fe); > >
Get the File Extension of a File Using contains() and lastIndexOf() Method in Java
The contains() method is used to check whether the specified char is present in the string or not and the lastIndexOf() method returns an index value of the specified char which is passed into substring() method to get file extension. We use these methods in this code to get file extension. See the example below.
public class SimpleTesting public static void main(String[] args) String fileName = "folder\s.gr\fg\student-records.pdf"; String fe = ""; if (fileName.contains(".")) fe = fileName.substring(fileName.lastIndexOf(".")+1); System.out.println("File extension is : "+fe); > >
Get the File Extension of a File Using ternary operators in Java
If you are comfortable with ternary operators( ?, : ) then use it with substring() and lastIndexOf() method. It reduces the line of code and returns the result in a single statement.
public class SimpleTesting public static void main(String[] args) String fileName = "folder\s.gr\fg\student-records.pdf"; String fe = ""; if (fileName.contains(".")) int i = fileName.lastIndexOf('.'); fe = i > 0 ? fileName.substring(i + 1) : ""; > System.out.println("File extension is : "+fe); > >
Get the File Extension of a File Using stream() Method in Java
We can use stream() method of Arrays class to convert the file name into stream and use split() method to break the file name from the dot( . ). See the example below.
import java.util.Arrays; public class SimpleTesting public static void main(String[] args) String fileName = "folder\s.gr\fg\student-records.pdf"; String fe = ""; if (fileName.contains(".")) fe = Arrays.stream(fileName.split("\\.")).reduce((a,b) -> b).orElse(null); > System.out.println("File extension is : "+fe); > >
Get the File Extension of a File Using Regex in Java
This is another solution that uses regex package. The compile() and matcher() method of Pattern class is used to fetch extension of the file in this Java example. See the example below.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class SimpleTesting public static void main(String[] args) String fileName = "folder\s.gr\fg\student-records.pdf"; String fe = ""; final Pattern PATTERN = Pattern.compile("(.*)\\.(.*)"); Matcher m = PATTERN.matcher(fileName); if (m.find()) fe = m.group(2); > System.out.println("File extension is : "+fe); > >
Related Article — Java IO
Related Article — Java File
Write a java program to find File Extension.
Write a program to read a file name as a string and find out the file extension and return it as output. For example, the file sun.gif has the extension gif.
Input and Output Format
- Input consists of a string that corresponds to a file name.
- The output consists of a string(extension of the input string (filename)).
Refer sample output for formatting specifications
Sample Input 1:
Sample Output 1:
Program to Find File Extension in Java
- Input file name from the user as a string.
- Pass the name to extensionString() method.
- Inside the method, create an object of string tokenizer for the specified string and separate the token with ‘.’ (dot) as a delimiter.
- Now, get the token before the ‘.’ (dot) by calling nextToken().
- At last, return it to the user.
import java.util.*; public class Main < public static void main(String[] args) < Scanner sc = new Scanner(System.in); String s1 = sc.nextLine(); System.out.println(extensionString(s1)); >public static String extensionString(String s1) < StringTokenizer t = new StringTokenizer(s1, "."); t.nextToken(); String s2 = t.nextToken(); return s2; >>
Output
Get File Extension using Library
- You need to create a Maven project using any IDE (We are using Eclipse IDE)
- Next, add the following dependency into the pom.xml file
- At last, use the utility class to fetch the extension name of the file and call the getExtension() method.
Program to get extension file in Java using Apache Common IO
package com.demo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.commons.io.FilenameUtils; public class Main < public static void main(String args[]) throws IOException < BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String s1 = bf.readLine(); System.out.print(FilenameUtils.getExtension(s1)); >>
Output
Extract File Extension using Guava Library
- You need to create a Maven project using any IDE (We are using Eclipse IDE)
- Next, add the following dependency into the pom.xml file
com.google.guava guava 31.0.1-jre
- At last, use the utility class to fetch the extension name of the file and call the getFileExtension() method.
Program to get the File Extension in Java
package com.IPAddress; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import com.google.common.io.Files; public class FileExtension < public static void main(String args[]) throws IOException < BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String s1 = bf.readLine(); System.out.print(Files.getFileExtension(s1)); >>
Output
Thus, in this way, we learned how to find the extension of files in Java.