Open In App

How to get the file extension in Java?

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, a File Extension refers to the characters after the “.” in a file name. It denotes the file type. For example, in the file name document.pdf, the file extension is pdf. This indicates that the file is a PDF format file.

In this article, we will learn how to get the file extension in Java.

Example Input and Output:

Input: filePath = “\\Users\\Documents\\document.txt”
Output: txt

Input: filePath = “\\Users\\Documents\\image.png”
Output: png

Input: filePath = “\\Users\\Documents\\config_file”
Output: No extension

A dot separates the filename from its file extension. For instance, “picture.jpg” has the extension “jpg ” which tells us it’s an image file. By extracting this extension your program can determine the type of file. Take action, like opening it with the right software or processing its content based on its format.

Regular Expression: fileName.fileExtention

Program to Get the file extension in Java

Java offers various methods to complete this task. Here are the three most common approaches:

Approach 1: Manipulating strings manually

In this approach, we can utilize string manipulation to find the instance of the dot “.”. Then extract the characters that come after it. It doesn’t rely on any libraries. It is straightforward, for simple scenarios. It does necessitate handling of special cases such as files without extensions or, with multiple dots.

Example: In this example, we will find the extension of the given file by manipulating the string manually.

Java




// Java program to get the file extension
// By manipulating String manually
import java.nio.file.Path;
public class StringManipulationExtractor {
  
    public static void main(String[] args) {
        // specify a file path
        String filePath = "C:\\Users\\Documents\\myFile.txt";
  
        // extract the filename from the path
        String filename = filePath.substring(filePath.lastIndexOf('\\') + 1);
  
        // find the last occurrence of '.' in the filename
        int dotIndex = filename.lastIndexOf('.');
  
        String extension = (dotIndex > 0) ? filename.substring(dotIndex + 1) : "";
  
        System.out.println("Extension: " + extension);
    }
}


Output

Extension: txt


Explanation of the above Program:

  • This Java program extracts the file extension from a given file path by manipulating the string manually.
  • It first extracts the filename from the path, then finds the last occurrence of ‘.’ in the filename to determine the extension.
  • At last, it prints the extracted extension.

Approach 2: By Using Java 8 Streams

This technique makes use of stream features to separate the filename using the dot “.” and obtain the part, which indicates the extension. This approach is compact and clear, for individuals who are familiar with streams. It can be combined with other stream operations. However it necessitates Java 8 or a newer version. It may have reduced efficiency when dealing with large datasets.

Example: In this example we will find the extension of the given file by Java stream.

Java




// Java program to get the file extension using Stream
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
  
class Java8StreamsExtractor {
  
    public static void main(String[] args) {
        // Specify a file path
        String filePath = "C:\\Users\\Documents\\report.pdf";
  
        // Create a Path object for robust path handling
        Path path = Paths.get(filePath);
  
        // Extract the filename from the Path and split it into parts
        String[] filenameParts = path.getFileName().toString().split("\\.");
  
        // Extract the extension using a stream and reduce it to the last part
        String extension = Arrays.stream(filenameParts)
                                .reduce((a, b) -> b)
                                .orElse("");
  
        System.out.println("Extension: " + extension);
    }
}


Output

Extension: pdf


Explanation of the above Program:

  • This Java program extracts the file extension from a given file path using Java 8 streams.
  • It splits the file name into parts using dots, then uses a stream to extract the last part, representing the extension.
  • At last, it prints the extracted extension.

Approach 3: getExtension() Method

The Path class, in Java’s package provides a method called getFileName().toString().split(“\\. “)[1] which allows direct access to the file extension. This approach is concise and dependable although it assumes familiarity with the Path class. For developers who’re comfortable with Java NIO libraries this method offers a convenient and efficient solution, for extracting file extensions.

Example: In this example we will find the extension of the given file by getExtension() method.

Java




// Java program to get the file extension
// By using getExtension() method
import java.nio.file.Path;
import java.nio.file.Paths;
  
public class FileExtensionExtractor {
  
    public static String getExtension(Path path) {
        String fileName = path.getFileName().toString();
        int dotIndex = fileName.lastIndexOf('.');
  
        // handle cases with no extension or multiple dots
        if (dotIndex == -1 || dotIndex == fileName.length() - 1) {
            return "";          // no extension found
        } else {
            return fileName.substring(dotIndex + 1);
        }
    }
  
    public static void main(String[] args) {
        Path filePath1 = Paths.get("C:\\Users\\Documents\\document.pdf");
        Path filePath2 = Paths.get("C:\\Users\\Documents\\report");    // no extension
        Path filePath3 = Paths.get("C:\\Users\\Documents\\config.sys.old");   // multiple dots
  
        System.out.println("Extension of " + filePath1 + ": " + getExtension(filePath1)); 
        System.out.println("Extension of " + filePath2 + ": " + getExtension(filePath2));  
        System.out.println("Extension of " + filePath3 + ": " + getExtension(filePath3)); 
    }
}


Output

Extension of C:\Users\Documents\document.pdf: pdf
Extension of C:\Users\Documents\report: 
Extension of C:\Users\Documents\config.sys.old: old


Explanation of the above Program:

  • The getExtension() method takes a Path object as input and extracts the file name from it.
  • Using the lastIndexOf() method, it finds the last occurrence of the dot character in the file name.
  • If no dot is found or the dot is at the end of the file name, it means there is no extension, so it returns an empty string.
  • Or else, it extracts the substring after the dot as the file extension.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads