Tuesday, September 19, 2006

Getting file extension

Java doesn't give you a way to get the extension of a file so you must do it yourself.

Usually you will get the position of the dot then use it to extract the extension. But it is not a correct way. Why? Because it depends. Depends on what? Depends on you and the OS you target.

If you use Windows, it's OK. Files in Windows can have extension. But in *nix, it's a different story. So you target to run your application both in Windows and *nix, you should consider this problem.

If your application target to run on Windows only, it's fine if you use the position of the dot to extract the extension (but remember, you must use lastIndexOf("."), not indexOf(".") because in Windows, extension will be determine by the position of the dot and from right to left of filename, not from left to right).

The below code fragment runs well in Windows and Linux.

public String getExtension(File file) {
String osName = System.getProperty("os.name");

if (osName.startsWith("Windows")) {
String filename = file.getName();
int index = filename.lastIndexOf(".");

if (index > 0 && index < filename.length() - 1) {
// extesion in Windows doesn't include the dot
// so we must use (index + 1) to substring
return filename.substring(index + 1).toLowerCase();
} else if (index == filename.length() - 1) {
// the dot is the last character in filename
// so extension is blank
return "";
}

// otherwise, this file doesn't have extension
// so we should return null
}

return null;
}


Update: Correct the source code

No comments: