How to Get File Extension

JavaJavaBeginner
Practice Now

Introduction

In this step-by-step lab, we will learn how to retrieve the extension of a file in Java programming language. The extension of a file indicates its type, which helps us differentiate between various types of files such as pdf, txt, doc, etc. Retrieving the file extension is important when dealing with files as it helps to ensure that the right type of files are handled in the right way.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/recursion("`Recursion`") java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/FileandIOManagementGroup -.-> java/files("`Files`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/if_else("`If...Else`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/recursion -.-> lab-117437{{"`How to Get File Extension`"}} java/scope -.-> lab-117437{{"`How to Get File Extension`"}} java/classes_objects -.-> lab-117437{{"`How to Get File Extension`"}} java/modifiers -.-> lab-117437{{"`How to Get File Extension`"}} java/oop -.-> lab-117437{{"`How to Get File Extension`"}} java/packages_api -.-> lab-117437{{"`How to Get File Extension`"}} java/files -.-> lab-117437{{"`How to Get File Extension`"}} java/identifier -.-> lab-117437{{"`How to Get File Extension`"}} java/arrays -.-> lab-117437{{"`How to Get File Extension`"}} java/data_types -.-> lab-117437{{"`How to Get File Extension`"}} java/if_else -.-> lab-117437{{"`How to Get File Extension`"}} java/operators -.-> lab-117437{{"`How to Get File Extension`"}} java/output -.-> lab-117437{{"`How to Get File Extension`"}} java/strings -.-> lab-117437{{"`How to Get File Extension`"}} java/variables -.-> lab-117437{{"`How to Get File Extension`"}} java/string_methods -.-> lab-117437{{"`How to Get File Extension`"}} java/system_methods -.-> lab-117437{{"`How to Get File Extension`"}} end

Create a Java file

Create a new Java file using the following command:

touch ~/project/FileExtension.java

Define the Java Class

import java.io.IOException;

public class FileExtension {
    public static void main(String[] args) throws IOException {

    }
}

Define the Main Method

In this step, we will define the main method to accept a filename from the user and extract its extension.

import java.io.IOException;

public class FileExtension {
    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            String filename = args[0];
            int index = filename.lastIndexOf(".");
            if (index > 0) {
                String extension = filename.substring(index + 1);
                System.out.println("File extension: " + extension);
            } else {
                System.out.println("No file extension found");
            }
        } else {
            System.out.println("Please provide a filename");
        }
    }
}

In the above code block, we are checking if a filename is provided by the user. If no filename is provided, it will prompt the user to provide a filename. We then use the lastIndexOf() method to get the index of the last dot in the filename which marks the beginning of the extension. If no dot is found in the filename, it suggests that the file has no extension. In both cases, we inform the user through command line output.

Compile the Java code

To compile the Java code, run the following command in the terminal:

javac ~/project/FileExtension.java

Execute the Java Program

To execute the Java program, run the following command:

java FileExtension filename.extension

where 'filename.extension' is the path and name of your file which you want to retrieve the file extension of.

Test the Java Program

Let's test the program by executing the program several times with different file extensions:

java FileExtension document.txt
java FileExtension image.png
java FileExtension music.mp3

Handling multiple file extensions

A file can have multiple extensions, separated by dot such as .tar.gz or .tar.bz2. In these cases, we can modify the code in Step 3 as follows.

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            String filename = args[0];
            int index = filename.indexOf(".");
            int lastIndex = filename.lastIndexOf(".");
            if (index > 0 && lastIndex > 0 && lastIndex > index) {
                String extension = filename.substring(lastIndex + 1);
                System.out.println("File Extension: ." + extension);
            } else {
                System.out.println("No file extension found");
            }
        } else {
            System.out.println("Please provide a filename");
        }
    }
}

In the above code block, we are first checking if the filename has multiple dots to identify multiple extensions. If multiple dots are found, we extract the last extension by using the lastIndexOf() method with an additional +1 to remove the dot symbol.

Compile the Java Code

Compile the Java code using the following command in the terminal:

javac ~/project/FileExtension.java

Test the Java Program

Let's test the program by executing it with multiple file extensions as follows:

java FileExtension document.pdf
java FileExtension image.png
java FileExtension music.mp3
java FileExtension archive.tar.gz

Summary

In this lab, we learnt how to retrieve the extension of a file in Java programming language. We wrote a Java program that accepts a filename from the user and extracts its extension to determine its type. We demonstrated how to handle files with multiple extensions using the indexOf() and lastIndexOf() methods.

Other Java Tutorials you may like