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. java.io.File 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;

import java.io.File;

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.

Comments

  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. abhayRSingh says:

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

  4. Daniele says:

    Works great! Thank you !

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages