开发者

Remove the extension of a file [duplicate]

开发者 https://www.devze.com 2023-04-08 17:40 出处:网络
This question already has answers here: How do I trim a file extension from a String in Java? (24 answers)
This question already has answers here: How do I trim a file extension from a String in Java? (24 answers) Closed 6 years ago.

Given a filename like:

 package.zip    image.jpeg   video.avi etc

I'd like to remove the extension if exists. How can I m开发者_Python百科ake 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.


myString = myString.replaceAll("\\.\\w+", "");


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

0

精彩评论

暂无评论...
验证码 换一张
取 消