How to get File Extension in Java

How to get File Extension in Java?

In this Example we are going to learn how to get File extension in Java

Example 1:

import org.apache.commons.io.FilenameUtils;
 public class GetFileExtension {
  public static void main(String[] args){
        String strFileName = "D:/java/text.txt";
         String strExtension = FilenameUtils.getExtension(strFileName);        
            System.out.println("Extension is: " + strExtension);
     }
}

Output

Extension is: txt 

 

Example 2:

 
public class GetFileExtension {
 public static void main(String[] args){
        String strFileName = "D:/java/text.txt";
         String strFileExtension = "";
            
            int intLastDotPosition = strFileName.lastIndexOf(".");
            int intLastSlashPosition = strFileName.lastIndexOf("/");
            if( intLastDotPosition > intLastSlashPosition ){
                strFileExtension = strFileName.substring(intLastDotPosition + 1);
            }
            System.out.println("File extension is: " + strFileExtension);
    }
}

Output

File Extension is: txt