Given a filename like:
package.zip image.jpeg video.avi etc
I'd like to remove the extension if exists. How can I make this in Java? THanks!
Something like
if (name.indexOf(".") > 0)
name = name.substring(0, name.lastIndexOf("."));
The index check avoids turning hidden files like ".profile" into "", and the lastIndexOf() takes care of names like cute.kitty.jpg.
Use Apache Commons IO, FilenameUtils.getBaseName(String filename)
or removeExtension(String filename), if you need the path too.
Here is a slightly more robust version:
public static String stripExtension(final String s)
{
return s != null && s.lastIndexOf(".") > 0 ? s.substring(0, s.lastIndexOf(".")) : s;
}
Gracefully handles null, cases where there is nothing that looks like an extension and doesn't molest files that start with a ., this also handles the .kitty.jpg problem as well.
This will handle most general cases in a controlled environment, if the suffix isn't actually an extension, just something . separated then you need to add some checking to see if the trailing part actually is an extension you recognize.
String result = filename.substring(0, filename.lastIndexOf("."))
Do check to see if the filename has a . before calling substring().
String name = filename.lastIndexOf('.') > filename.lastIndexOf(File.separatorChar) ?
filename.substring(0, filename.lastIndexOf('.'))
: filename;
The comparison checks that the filename itself contains a ., otherwise the string is returned unchanged.
Pattern suffix = Pattern.compile("\\.\\p{Alnum}+$");
Matcher m = suffix.matcher(filename);
String clearFilename = m.replaceAll("");
The problem of this solution is that, depending of your requirements, you need to extend it to support composed extensions, like filename.tar.gz, filename.tar.bz2
[]'s
And Past