extract extension from filename java code example

Example 1: java how to read file 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;
 
    }

Example 2: how to get filename without extension in java

FilenameUtils.removeExtension(fileNameWithExt);

Example 3: java get filename without extension

String fname = file.getName();
int pos = fname.lastIndexOf(".");
if (pos > 0) {
    fname = fname.substring(0, pos);
}

Tags:

Java Example