×

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

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Java Vs C++

Java Vs C++ Java and C++ both are Object Oriented Programming languages. Both languages are popular for competitive programming. C++ is used by many coders who have just started learning programming...

4 minutes read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 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.

Difference between next() and nextline() in Java

One of the simplest methods for receiving input of the basic data types, also including int, double, and strings, in Java, is to use the Scanner class, which is part...

3 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.