删除 Java 中的文件扩展名

2022-09-01 20:00:40

(不包括任何外部库。

在Java中删除文件名扩展名而不假设文件名的最有效方法是什么?

一些示例和预期结果:

  • 文件夹 > 文件夹
  • 你好.txt >你好
  • read.me >阅读
  • hello.bkp.txt > hello.bkp
  • 奇怪。。名字>奇怪。
  • .hidden > .hidden

(或者最后一个应该被隐藏吗?

编辑:原始问题假定输入是文件名(而不是文件路径)。由于一些答案正在谈论文件路径,因此此类函数也应该在以下情况下工作:

  • rare.folder/hello > rare.folder/hello

西尔万·M的回答很好地处理了这个特殊情况。


答案 1

使用 apache http://commons.apache.org/io/ 中的 common io

公共静态字符串删除扩展(字符串文件名)

仅供参考,源代码在这里:

http://commons.apache.org/proper/commons-io/javadocs/api-release/src-html/org/apache/commons/io/FilenameUtils.html#line.1025

Arg,我刚刚尝试了一些东西...

System.out.println(FilenameUtils.getExtension(".polop")); // polop
System.out.println(FilenameUtils.removeExtension(".polop")); // empty string

所以,这个解决方案似乎不是很好...即使使用常见的io,你也必须玩removeExtension() getExtension() indexOfExtension()...


答案 2

我将对此进行尝试,使用双参数版本,以删除一些特殊情况的检查代码,并希望使意图更具可读性。感谢Justin 'jinguy' Nelson提供了这种方法的基础:lastIndexOf

public static String removeExtention(String filePath) {
    // These first few lines the same as Justin's
    File f = new File(filePath);

    // if it's a directory, don't remove the extention
    if (f.isDirectory()) return filePath;

    String name = f.getName();

    // Now we know it's a file - don't need to do any special hidden
    // checking or contains() checking because of:
    final int lastPeriodPos = name.lastIndexOf('.');
    if (lastPeriodPos <= 0)
    {
        // No period after first character - return name as it was passed in
        return filePath;
    }
    else
    {
        // Remove the last period and everything after it
        File renamed = new File(f.getParent(), name.substring(0, lastPeriodPos));
        return renamed.getPath();
    }
}

对我来说,这比特殊大小写的隐藏文件和不包含点的文件更清晰。它也读起来更清楚,我理解你的规格是什么;类似于“删除最后一个点及其后面的所有内容,假设它存在并且不是文件名的第一个字符”。

请注意,此示例还暗示字符串作为输入和输出。由于大多数抽象都需要对象,因此如果这些也是输入和输出,则会稍微清楚一些。File