删除Java中的文件扩展名

hpi*_*que 23 java file-extension

(不包括任何外部库.)

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

一些例子和预期结果:

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

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

编辑:原始问题假设输入是文件名(不是文件路径).由于一些答案是在讨论文件路径,因此这些函数也适用于以下情况:

  • rare.folder/hello> rare.folder /你好

Sylvain M的答案很好地处理了这个特例.

sly*_*7_7 26

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

public static String removeExtension(String filename)

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

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
Run Code Online (Sandbox Code Playgroud)

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


And*_*yle 12

lastIndexOf为了删除一些特殊情况检查代码,我将要使用两个arg版本,并希望使意图更具可读性.幸得贾斯汀"jinguy"尼尔森提供这种方法的基础:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

对我而言,这比特殊外壳隐藏文件和不包含点的文件更清晰.它也更清楚我理解你的规范; 类似于"删除最后一个点及其后的所有内容,假设它存在且不是文件名的第一个字符".

请注意,此示例还将字符串视为输入和输出.由于大部分抽象都需要File对象,如果那些是输入和输出,那么它将更加清晰.


jjn*_*guy 11

这将采用文件路径,然后返回没有扩展名的文件的新名称.

public static String removeExtention(String filePath) {
    File f = new File(filePath);
    // if it's a directory, don't remove the extention
    if (fisDirectory()) return f.getName();
    String name = f.getName();
    // if it is a hidden file
    if (name.startsWith(".")) {
        // if there is no extn, do not rmove one...
        if (name.lastIndexOf('.') == name.indexOf('.')) return name;
    }
    // if there is no extention, don't do anything
    if (!name.contains(".") return name;
    // Otherwise, remove the last 'extension type thing'
    return name.substring(0, name.lastIndexOf('.'))
}
Run Code Online (Sandbox Code Playgroud)

人们应该注意到这是写在我的上网本上,在微小的SO编辑器框中.此代码不适用于生产.它只是服务器作为我如何从文件名中删除扩展名的良好的第一次尝试示例.

  • 你需要检查`name.lastIndexOf('.')!= -1`,否则最后一个`substring`调用将抛出异常.由于hgpc表示不假设文件名,这似乎应该正确处理的情况. (2认同)