Java Program to Get the File Extension

In this program, we will learn to fetch the extension of a file. In Java, you can get the file extension of a file using the File class and the getName() and lastIndexOf() methods of the String class.

The File class is used to represent a file or directory in the file system, while the getName() method returns the name of the file or directory and the lastIndexOf() method returns the index of the last occurrence of a specified character or substring.

Here is an example of how you can get the file extension of a file in Java.


public class FileExtensionExample {
  public static void main(String[] args) {
    String fileName = "example.txt";
    File file = new File(fileName);

    String fileNameWithoutExt = file.getName()
            .substring(0, file.getName().lastIndexOf("."));
    String fileExtension = file.getName()
            .substring(file.getName().lastIndexOf(".") + 1);

    System.out.println("File name: " + fileNameWithoutExt);
    System.out.println("File extension: " + fileExtension);
File name: example
File extension: txt

In this example, the main method first creates a File object with the file name "example.txt" and then calls the getName() method on it to get the name of the file. Then, it uses the lastIndexOf() method to find the index of the last occurrence of the "." character in the file name. Next, it uses the substring() method to extract the extension of the file. Finally, it prints the file name and the file extension to the console.

You could also use the Path class and its getFileName() method, and Paths.get() method to get the Path object, then use the toString() method on the Path object to get the file name, then use the same way to get the extension.

It's important to note that this method assumes that the file name has a valid extension, if the file name doesn't have an extension this method will throw an exception.

Also, if you're dealing with a file that has multiple dots in its name, this method will only return the last part after the last dot.