How to Get File Extension in Java

Filed Under: Java

Sometimes while working with files, we need to process them differently based on their type. doesn’t have any method to get the file extension, here I am providing a utility method to get the file extension in java.

Java Get File Extension

The extension of a file is the last part of its name after the period (.). For example, Java source file extension is “java” and you will notice that file name always ends with “.java”.

We can use this file name and extension logic to retrieve the last part of the file name and get the extension of the file.

package com.journaldev.files;


public class GetFileExtension {

     * Get File extension in java
     * @param args
    public static void main(String[] args) {
        File file = new File("/Users/pankaj/java.txt");
        System.out.println("File extension is: "+getFileExtension(file));
        //file name without extension
        file = new File("/Users/pankaj/temp");
        System.out.println("File extension is: "+getFileExtension(file));
        //file name with dot
        file = new File("/Users/pankaj/java.util.txt");
        System.out.println("File extension is: "+getFileExtension(file));
        //hidden files without extension
        file = new File("/Users/pankaj/.htaccess");
        System.out.println("File extension is: "+getFileExtension(file));

    private static String getFileExtension(File file) {
        String fileName = file.getName();
        if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
        return fileName.substring(fileName.lastIndexOf(".")+1);
        else return "";


Output of the above program is:

File extension is: txt
File extension is: 
File extension is: txt
File extension is: 

Note that here I am not checking if the file exists or not. However, in real programming scenarios, you should check that file exists or not before processing further.

You can checkout more Java IO examples from our GitHub Repository.


  1. Gary says:

    I think it fails if there is a . in a folder name and no . in the filename.

  2. CM says:

    Suberb, thanks very much. Your solution didnot just get the extension, but you took care of extesion-less file and hidden ones. Good Work…

  3. navin says:

    Super g..

  4. abhayRSingh says:

    Thanks alot Sir for the much needed help at a crucial point of time.

  5. Daniele says:

    Works great! Thank you !

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors