Files are usually known through their extensions. An extension differentiates the file from another file. It recognizes the file type. To find the extension from its file is a common task.
You can see in the give example, we have created an object of class File and specify a text file as an argument. The method getName() returns the name of the file. Then we have used substring() method to return a new string consists of file extension.
import java.io.*; public class ExtensionJava { public static void main(String[] args) { File file = new File("file.txt"); String fname = file.getName(); String ext = fname.substring(fname.lastIndexOf('.') + 1, fname.length()); System.out.println("Extension of file " + fname + " is: " + ext); } }