Get File Extension Using Java

 Posted On  | Yashwant Chavan 

Most of the time we required file extension while processing File I/O operation. But in Java don't have any in build File API which will give you file extension. So below written utility method will help you to get the file extension.

Java File Extension Example



public class JavaExtensionExample {
    public static void main(String[] args) {
        String extension = getFileExtension(new File("C:\\article\\"));
        System.out.println("File Extension :- " + extension);
        extension = getFileExtension(new File("C:\\article\\eclipse.png"));
        System.out.println("File Extension :- " + extension);

    private static String getFileExtension(File file) {
        String extension = "";

        try {
            if (file != null && file.exists()) {
                String name = file.getName();
                extension = name.substring(name.lastIndexOf("."));
        } catch (Exception e) {
            extension = "";

        return extension;



If you want to remove the period "." from the file extension , You can add name.lastIndexOf(".") + 1, So it will remove the period from output.


Let us compile and execute the above program.

File Extension :- .zip
File Extension :- .png


Hope this Tutorial is useful to you, Please fill free to provide your comments if there is any problem. Thanks

© 2018

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0296 seconds.