How can we get file extension in Java

0 votes
I am working on different files. How can I find file extension using Java?
May 8, 2018 in Java by Daisy
• 8,140 points
• 5,263 views

1 answer to this question.

0 votes

To get the file extension, we can use FilenameUtils.getExtension() method from Apache Commons IO.

String f1 = FilenameUtils.getExtension("file1.txt"); // returns "txt"
String f2 = FilenameUtils.getExtension("file2.exe"); // returns "exe"
answered May 8, 2018 by Parth
• 4,640 points
0 votes
In Java, you can find the file extension by using the File class and its getName() method to retrieve the name of the file. Then, you can use string manipulation methods such as lastIndexOf() and substring() to extract the file extension. Here's a simple example:

import java.io.File;

public class FileExtensionExample {
    public static void main(String[] args) {
        String fileName = "example.txt"; // Replace this with the actual file name
        String fileExtension = getFileExtension(fileName);
        System.out.println("File extension: " + fileExtension);
    }
    
    public static String getFileExtension(String fileName) {
        if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".")+1);
        } else {
            return ""; // No file extension found
        }
    }
}

In this example, the getFileExtension() method takes the file name as input and returns the file extension. It checks if the file name contains a dot ('.') character, which indicates the presence of a file extension. If found, it extracts the substring after the last dot, which represents the file extension.
answered Apr 3, 2024 by kevin

edited Mar 5, 2025

Related Questions In Java

0 votes
2 answers

How can I create File and write data in it using Java?

import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFiles{ ...READ MORE

answered Jul 26, 2018 in Java by samarth295
• 2,220 points
• 5,162 views
0 votes
4 answers

How can we compare dates in java?

public static String daysBetween(String day1, String day2) ...READ MORE

answered Sep 5, 2018 in Java by Sushmita
• 6,920 points
• 4,028 views
0 votes
2 answers

How can we remove an element from an array in Java?

You can use ArrayUtils class remove method ...READ MORE

answered May 24, 2018 in Java by UshaK
• 4,842 views