Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Java Program to Get the File Extension

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The extension of a file is the last part of its name after the period (.). For example, the Java source file extension is “java”, and you will notice that the file name always ends with “.java”. Getting the file extension in Java is done using the File class of Java, i.e., probeContentType() method. The File class is Java’s representation of a file or directory pathname. The File class contains several processes for working with the pathname, deleting and renaming files, creating new directories, listing the directory contents, and determining several common attributes of files and directories.

probeContentType() Method

The probeContentType() is a method that comes predefined in the Java File class. The parameter to this method is passed the path of the file.

  • Parameters: A path of the file.
  • Return value: It returns a string(extension).

Syntax: In Java, we can get the filename by – 

File file = new File("/home/mayur/");
String fileName = file.getName();

fileType = Files.probeContentType(f.toPath());

Below is the implementation of the problem statement: 


// Java Program to Get the File Extension
import java.nio.file.Files;
public class GFG {
    public static void main(String[] args)
        // File location
        File f = new File("/home/mayur/");
        // If file exists
        if (f.exists()) {
            String fileType = "Undetermined";
            String fileName = f.getName();
            String extension = "";
            int i = fileName.lastIndexOf('.');
            if (i > 0) {
                extension = fileName.substring(i + 1);
            try {
                    = Files.probeContentType(f.toPath());
            catch (IOException ioException) {
                    "Cannot determine file type of "
                    + f.getName()
                    + " due to following exception: "
                    + ioException);
            // Print Extension
                "Extension used for file is -> " + extension
                + " and is probably " + fileType);
        else {
            System.out.println("File does not exist!");


Java Program to Get the File Extension

In the above example,

  • file.getName() – Returns the file’s name and store it in a String variable.
  • fileName.lastIndexOf(‘.’) – Returns the last occurrence of character. Since all file extension starts with ‘.’, we use the character ‘.’.
  • fileName.substring() – Returns the string after character ‘.’.

My Personal Notes arrow_drop_up
Last Updated : 22 Oct, 2021
Like Article
Save Article
Similar Reads
Related Tutorials