Languages
[Edit]
EN

Java - get file extension

0 points
Created by:
Maggotta
289

In this article, we would like to show you how to get a file extension in Java.

Practical example

In this example, we use String.lastIndexOf method to get the file extension.

import java.io.*;


public class Example {

    public static void main(String[] args) throws IOException {
        String[] files = {
                "\\path\\example.txt",
                "\\path\\example.exe",
                "\\path\\example.pdf",
                ".",
                "..",
                "\\path\\makefile",
                "\\path\\.htaccess",
                "\\path\\.tar.gz"
        };
        String extension = "";

        for (String path : files) {
            int index = path.lastIndexOf('.');
            if (index > 0) {
                extension = path.substring(index + 1);
            }
            System.out.println(extension);
        }
    }
}

Output:

txt
exe
pdf
pdf


htaccess
gz
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join