问题

在Java中修剪后缀的最有效方法是什么,如下所示:

title part1.txt
title part2.html
=>
title part1
title part2

#1 热门回答(243 赞)

这是我们自己不应该做的那种代码。使用库来获取平凡的东西,为大脑保存你的大脑。

在这种情况下,我建议使用FilenameUtils.removeExtension()fromApache Commons IO


#2 热门回答(200 赞)

str.substring(0, str.lastIndexOf('.'))

#3 热门回答(82 赞)

由于在单线程中使用String.substringString.lastIndex是好的,因此在能够处理某些文件路径方面存在一些问题。

以下面的路径为例:

a.b/c

使用单行将导致:

a

那是不对的。

结果应该是c,但由于该文件没有扩展名,但路径中有一个名称为a.的目录,因此单线程方法被欺骗为提供路径的一部分作为文件名,这是不正确的。
需要检查
受到skaffman's answer的启发,我看了Apache Commons IOFilenameUtils.removeExtension方法。

为了重新创建它的行为,我写了一些新方法应该完成的测试,其中包括:

Path                  Filename
--------------        --------
a/b/c                 c
a/b/c.jpg             c
a/b/c.jpg.jpg         c.jpg

a.b/c                 c
a.b/c.jpg             c
a.b/c.jpg.jpg         c.jpg

c                     c
c.jpg                 c
c.jpg.jpg             c.jpg

(这就是我所检查的全部 - 可能还有其他我应该忽略的检查。)
执行
以下是我对removeExtension方法的实现:

public static String removeExtension(String s) {

    String separator = System.getProperty("file.separator");
    String filename;

    // Remove the path upto the filename.
    int lastSeparatorIndex = s.lastIndexOf(separator);
    if (lastSeparatorIndex == -1) {
        filename = s;
    } else {
        filename = s.substring(lastSeparatorIndex + 1);
    }

    // Remove the extension.
    int extensionIndex = filename.lastIndexOf(".");
    if (extensionIndex == -1)
        return filename;

    return filename.substring(0, extensionIndex);
}

使用上述测试运行此removeExtension方法将产生上面列出的结果。

使用以下代码测试该方法。由于这是在Windows上运行的,路径分隔符是a\,当用作aStringliteral的一部分时,必须使用a\进行转义。

System.out.println(removeExtension("a\\b\\c"));
System.out.println(removeExtension("a\\b\\c.jpg"));
System.out.println(removeExtension("a\\b\\c.jpg.jpg"));

System.out.println(removeExtension("a.b\\c"));
System.out.println(removeExtension("a.b\\c.jpg"));
System.out.println(removeExtension("a.b\\c.jpg.jpg"));

System.out.println(removeExtension("c"));
System.out.println(removeExtension("c.jpg"));
System.out.println(removeExtension("c.jpg.jpg"));

结果是:

c
c
c.jpg
c
c
c.jpg
c
c
c.jpg

结果是该方法应该满足的测试中概述的期望结果。


原文链接