How To Get Extension of a File in Java?

Below Java code example show how to retrieve the extension of File using Java File object –


/**********************************************************************************
 * Created on 04-2011 Copyright(c) https://kodehelp.com All Rights Reserved.
 **********************************************************************************/
package com.kodehelp.javaio;

import java.io.File;

/**
 * Created by https://kodehelp.com
 * Date: 4/28/11
 */
public class ExtensionOfFile {
    public static final String DOT_SEPARATOR = ".";

    public static void main(String [] args){
        File file = new File("TESTFILE.DAT");
        System.out.println("EXTENSION OF FILE IS = "+getFileExtension(file));

    }
    /**
     * This method takes File Object as parameter and returns the extension of the file.
     * @param file - a file object.
     * @return -String -the extension of the file.
     */
    public static String getFileExtension(File file) {
        if (file == null) {
            return null;
        }

        String name = file.getName();
        int extIndex = name.lastIndexOf(ExtensionOfFile.DOT_SEPARATOR);

        if (extIndex == -1) {
            return "";
        } else {
            return name.substring(extIndex + 1);
        }
    }
}

Output of this program will be –


EXTENSION OF FILE IS = DAT