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

package com.technicalkeeda.app;

import java.io.File;


public class JavaExtensionExample {
    public static void main(String[] args) {
        String extension = getFileExtension(new File("C:\\article\\mongodb-json.zip"));
        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.

Output

Let us compile and execute the above program.

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

Finish

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


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0322 seconds.