Get File Extension in Java

Get File Extension in Java | Here we will discuss how to get file extension in Java using different classes and libraries. We can either take the help of external Java libraries or we can develop our own logic to get the file extension in Java. For this, first, we will create a file object using the Java File class.

Example-1:-
File name = “Test.txt”
Extension of file = “txt”

Example-2:-
File name = “maven-3.8.6-settings.xml”
Extension of file = “xml”

Program to Get File Extension in Java using lastIndexOf() & substring()

To get the file extension we can take the help of the lastIndexOf() method of the Java String class. In a given file, we can identify extensions using the dot (‘.’) character. Example:- image.png, here “png” is the file extension, and “image” is the file name.

We should be using lastIndexOf() method instead of indexOf() method because there can be case where fileName also contains dot (‘.’) character. For example:- “maven-3.8.6-settings.xml”. The lastIndexOf() method of the String class returns the last index of the given character in the given string, and if the character doesn’t exist in the given string then it returns -1.

After getting the last index of the dot (‘.’) character, we can call the substring() method to get the substring from index+1 to the end of the string. Later we will convert the result to lowercase using the toLowerCase() method.

import java.io.File;

public class Main {
   private static String getExtension(String fileName) {
      if (fileName == null) {
         return null;
      }
      int lastDotIndex = fileName.lastIndexOf('.');
      return (lastDotIndex == -1) ? 
            "" : fileName.substring(lastDotIndex + 1).toLowerCase();
   }

   public static void main(String[] args) {
      File file = new File("Test.txt");
      String fileName = file.toString();
      String extension = getExtension(fileName);
      System.out.println("File name: " + fileName);
      System.out.println("Extension: " + extension);

      File file1 = new File("/home/user/Downloads/maven-3.8.6-settings.xml");
      System.out.println("Extension: " + getExtension(file1.toString()));

      File file2 = new File("Hello-World");
      System.out.println("Extension: " + getExtension(file2.toString()));
   }
}

Output:-

File name: Test.txt
Extension: txt
Extension: xml
Extension:

It will return the file extension without the dot “.”. Example:- file = “Test.txt” then it return “txt”. If you want to include the dot (‘.’) in file extension then we have to call fileName.substring(lastDotIndex).

return (lastDotIndex == -1) ?
        "" : fileName.substring(lastDotIndex).toLowerCase();

The same program can be written with the help of Java Stream as follows. Program to get file extension in Java with the help of Stream API:-

import java.io.File;
import java.util.Optional;

public class Main {
   private static Optional<String> getExtension(String fileName) {
      return Optional.ofNullable(fileName).filter(f -> f.contains("."))
            .map(f -> f.substring(fileName.lastIndexOf(".") + 1));
   }

   public static void main(String[] args) {
      File file = new File("Test.txt");
      String extension = getExtension(file.toString()).get();
      System.out.println("Extension: " + extension);
   }
}

Output:-

Extension: txt

Get File Extension in Java using Apache Commons IO

The Apache Commons IO contains FilenameUtils class which provides multiple methods for general file name and file path manipulation utilities. It has the getExtension() method which returns the extension of the given file.

Method syntax:- public static String getExtension(String fileName) throws IllegalArgumentException

The getExtension() method of FilenameUtils class of org.apache.commons.io returns the textual part of the fileName after the last dot. There must be no directory separator after the dot. It throws IllegalArgumentException in windows for file names like “foo.exe:bar.txt”. 

import java.io.File;

import org.apache.commons.io.FilenameUtils;

public class Main {
   public static void main(String[] args) {
      File file = new File("app-request.json");
      System.out.println("Extension: " +
           FilenameUtils.getExtension(file.toString()));
   }
}

Output:-

Extension: json

Get File Extension in Java using Guava  Library

By using Guava libraries (Guava: Google Core Libraries for Java), we can get the file extension. The Files class of Guava libraries contains the getFileExtension() method. Method syntax:- public static String getFileExtension​(String fullName)

It returns the file extension for the given file name, or the empty string if the file has no extension. The result does not include the ‘.’.

import java.io.File;

import com.google.common.io.Files;

public class Main {
   public static void main(String[] args) {
      File file = new File("script.py");
      System.out.println("Extension: " +
           Files.getFileExtension(file.toString()));
   }
}

Output:-

Extension: py

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.