Java program to get the file extension

https://w‮.ww‬theitroad.com

To get the file extension in Java, you can use the lastIndexOf() and substring() methods provided by the String class. Here is an example program that demonstrates how to get the file extension:

import java.io.File;

public class FileExtensionExample {
    public static void main(String[] args) {
        File file = new File("example.txt");
        String fileName = file.getName();
        String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println("File extension: " + fileExtension);
    }
}

In this program, we create a File object that represents a file with the name "example.txt". We then use the getName() method to get the name of the file as a String. We find the index of the last dot (".") character in the file name using the lastIndexOf() method, and add 1 to get the index of the first character of the file extension. We then use the substring() method to extract the file extension as a String.

When you run this program, you will get output like this:

File extension: txt

This shows that the file extension is correctly extracted from the file name.