Best Way To Get File Extension In Java

While programming java on many occasions we need to get extension of from file paths or file name. For this type of work apache commmons io lib provides very useful utility class know as FilenameUtils which have set of many useful function. You can use FilenameUtils.getExtension(filename) function get get extension of any file.

Here is example of FilenameUtils

String ext = FilenameUtils.getExtension("D:/test/textfile.txt");
System.out.println(ext);

If you do not want to use above lib then you can use following example to get file extension.

public class FileExtentionExample {
public static void main(String[] args) {
File file = new File("D:/test/textfile.txt");
System.out.println(getExtension(file.getAbsolutePath()));
System.out.println(getExtension(file.getName()));
}
public static String getExtension(String filename) {
if (filename == null) {
return null;
}
int extensionPos = filename.lastIndexOf(\'.\');
int lastUnixPos = filename.lastIndexOf(\'/\');
int lastWindowsPos = filename.lastIndexOf(\'\\\');
int lastSeparator = Math.max(lastUnixPos, lastWindowsPos);
int index = lastSeparator > extensionPos ? -1 : extensionPos;
if (index == -1) {
return "";
} else {
return filename.substring(index + 1);
}
}
}