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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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:
1 2 3 4 5 6 |
<span style="color: #008000;"><strong><code> File extension is: txt File extension is: File extension is: txt File extension is: </code></strong></span> |
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.