Get Extension Of File In Java

In this tutorial, we will learn or figure out how to get the extension of any file through the Java program easily. In Java, there is no built-in API to find the extension of a file but you can do this with the below program.

Get Extension Of A File In Java

As a rule, we need or required archive development while dealing with record input-yield tasks.

As already I mentioned there is no API in java to get the extension of a file but through the simple code, we can make it possible to find the file extension.

If you don’t know how to get the file extension then you are at the right place.

At first, we have to import a File package to deal with the file input-output stuff. We can add it by simply writing:-

import java.io.File;

The Below code will help you to achieve your goal:-

import java.io.File;
public class GetFileExtension
{
    public static void main(String[] args) 
        {
        File file=new File("Example.txt");
        File file2=new File("Example2.png");
        String extension="";
        String extension2="";
        try{
            if(file!=null || file.exists())
               {
                String name=file.getName();
                extension=name.substring(name.lastIndexOf("."));
            }
            }
        catch(Exception e)
        {
          extension="";
          
        }
        try{
            if(file2!=null || file2.exists())  
            {
                String name2=file2.getName();
                extension2=name2.substring(name2.lastIndexOf(".")); // this will give the extension of a fle
            }
            }
        
        catch(Exception e)
        {
            extension2="";
        }
        System.out.println("*****OUTPUT OF THE ABOVE CODE*****");
        System.out.println("Extension of a file 1 is"+extension);
        System.out.println("Extension of second file is"+extension2);
    }

You can identify any file extension through the above code.

The output of the following code will give the result:-

 

*****OUTPUT OF THE ABOVE CODE*****
Extension of a file 1 is.txt
Extension of second file is.png

You may also learn:

Leave a Reply

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