Java Get File Extension From Filename

Retrieving a file's extension in Java is a common task. This post will guide you through various methods to achieve this, with output for each example.

1. Using Java's String Methods 

Using built-in String methods, you can easily extract a file extension:

public class Main{
    public static String getFileExtension(String filename) {
        int lastIndexOf = filename.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return ""; // empty extension
        }
        return filename.substring(lastIndexOf);
    }
    
    public static void main(String[] args) {
        String filename = "example.txt";
        System.out.println(getFileExtension(filename));  
    }
}

Output:

.txt

2. Using Java's File Class 

Combine the File class's getName() method with String methods:

import java.io.File;
public class Main{
    public static String getFileExtension(File file) {
        String name = file.getName();
        int lastIndexOf = name.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return "";
        }
        return name.substring(lastIndexOf);
    }
    
    public static void main(String[] args) {
        File file = new File("example.txt");
        System.out.println(getFileExtension(file));  // Output: .txt
    }
}

Output:

.txt

3. Using Apache Commons IO 

With the Apache Commons IO library, extracting a file extension becomes even simpler:

import org.apache.commons.io.FilenameUtils;
public class Main{
    public static void main(String[] args) {
        String filename = "example.txt";
        String extension = FilenameUtils.getExtension(filename);
        System.out.println(extension);  // Output: txt
    }
}

Note: Add the Apache Commons IO library to your project to use this method.

4. Using Java's NIO Library 

Java's New I/O (NIO) provides a comprehensive approach:

import java.nio.file.Path;
import java.nio.file.Paths;

public class Main{
    public static String getFileExtension(Path path) {
        String name = path.getFileName().toString();
        int lastIndexOf = name.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return "";
        }
        return name.substring(lastIndexOf);
    }
    
    public static void main(String[] args) {
        Path path = Paths.get("core-java.pdf");
        System.out.println(getFileExtension(path));
    }
}

Output:

.pdf

Conclusion 

These methods provide diverse ways to extract file extensions in Java. Remember to validate and sanitize file extensions for security and accuracy. With this guide, you're set to handle file extensions effectively in Java.

File Handling Examples

Comments