×

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name.

Consider the file Demo.java as an example; Demo is the file name, and .java is the file extension, both of which indicate the file format.

In this section, we will learn how to use a Java program to obtain a file's extension.

Java File Class

  • The io package contains the definition of the Java File class. The java.nio package is another new Java package used to carry out input/output tasks. It first appears in JDK4.
  • It is utilized in the Java program to carry out certain file operations.
  • The File class has a variety of constructors and methods that can be used to rename, delete, or create new files, among other operations, using the file path name.
  • A File class instance must be created to use these constructors and methods.
  • Instances of the File class are immutable; thus, once they are created with a particular pathname, they cannot be modified.

How to Get the File Extension?

In Java, there are two ways to obtain file extensions.

The following program uses the File class to determine the file extension of the provided file we provide as input.

FileTypeDemo.java

import java.io.* ;  
import java.nio.file.Files ;  
public class FileTypeDemo   
{  
    /*main method*/  
    public static void main(String ar[])  
    {  
        /* declaring a File instance with the path of the File */  
        File f = new File("C:/Users/vishwanth/sn/dem.txt") ;  //location
        /* If file exists */  
        if(f.exists())   
        {  
            String fType = "Undetermined" ;  //undetermined
            String fName = f.getName() ;   
            String extension = "";  
            int i = fName.lastIndexOf('.') ;  //lastIndexOf() method
  
            if (i > 0)   
            {  
                extension = fName.substring(i + 1) ;  
            }  
            try   
            {  
                fType= Files.probeContentType(f.toPath()) ;  
            }  
            catch (IOException ioException)   //catches io exception
            {  
                System.out.println("Cannot determine type of file "+ f.getName()+ " due to the exception: "+ ioException) ;  
            }  
  
            /* Print the file extension. */  
            System.out.println("File Extension used is: " + extension + " and is probably " + fType) ;  
        }  
        else   
        {  
            System.out.println("File does not exist!") ;  //prints file does not exist
        }  
    }  
}  

Output:

Java File Extension

In the above-displayed image, the output for the above program is provided. As the file “dem.txt” is present, the program prints the file extension as txt for the file “dem”.

In the Java program cited above,

  • It creates an instance "f" of the File class from the io package. It produces an instance of the path that was supplied to the constructor.
  • The file existence is checked using an if statement on the following line. The variables for storing the file type, file name, and file extension will be created if the condition is proper.
  • The last occurrence of the character supplied as an argument is returned by the lastIndexOf() function.
  • substring() method is used to get the file extension after the period (.)
  • The nio package's probeContentType() method returns a string indicating the content type. Due to the possibility that it will raise an IOException, it is specified inside a try-catch block.
  • And last, a print() command is used to display the file extension and content type on the console.

Using Apache Commons IO Library

The Apache Commons IO component, adapted from the Java API, offers various ways to carry out multiple operations on files without first constructing an object of the file. The FilenameUtils.getExtension() method is employed in the code below to obtain the file extension.

GetFileExtensionApache.java

import java.io.IOException ;  
import org.apache.commons.io.FilenameUtils ;  
public class GetFileExtensionApache  
{  
    /* Driver Code */  
    public static void main(String []args)  
    {  
        try   
        {  
            usingFilenameUtils();  
        }  
        catch(IOException e)   
        {  
            System.out.println(e.getMessage()) ;  
        }  
    }  
    public static void usingFilenameUtils() throws IOException  
    {  
          /* now, provide the file path of the required file */
        String path = " C:/Users/vishwanth/sn/dem.txt" ;  
        System.out.println("Extension: " + FilenameUtils.getExtension(path)) ;  
    }  
}  

Output:

The getExtension() function of the FilenameUtils class is used in the Java code above to obtain the file extension without constructing a file object.

Java File Extension

The above-displayed image shows the output for the above program. The output contains the extension of the file provided in the program. As the file “dem' is a txt file, the program displays "Extension: txt" as its output.


Related Topics

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

Java Regular Expressions

Java Regular Expressions The Java Regex or Regular Expression is an API that defines a pattern for searching or manipulating strings. A regular expression is a pattern that can be as simple as...

8 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.