删除Java中的文件扩展名 [英] Remove filename extension in Java

查看:583
本文介绍了删除Java中的文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(不包括任何外部库。)

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

What's the most efficient way to remove the extension of a filename in Java, without assuming anything of the filename?

一些例子和预期结果:


  • 文件夹>文件夹

  • hello.txt> hello

  • read.me> read

  • hello.bkp.txt> hello.bkp

  • 怪异。名称>怪异。

  • .hidden> .hidden

  • folder > folder
  • hello.txt > hello
  • read.me > read
  • hello.bkp.txt > hello.bkp
  • weird..name > weird.
  • .hidden > .hidden

(或者最后一个只是隐藏?)

(or should the last one be just hidden?)

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

Edit: The original question assumed that the input is a filename (not a file path). Since some answers are talking about file paths, such functions should also work in cases like:


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

这个特殊情况由Sylvain M的答案处理得非常好。

This particular case is handled very well by Sylvain M's answer.

推荐答案

我将对此使用两个arg版本的 lastIndexOf 以便删除一些特殊的 - 案例检查代码,希望使意图更具可读性。归功于 Justin'jinguy'Nelson 提供的基础方法:

I'm going to have a stab at this that uses the two-arg version of lastIndexOf in order to remove some special-case checking code, and hopefully make the intention more readable. Credit goes to Justin 'jinguy' Nelson for providing the basis of this method:

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();
    }
}

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

To me this is clearer than special-casing hidden files and files that don't contain a dot. It also reads clearer to what I understand your specification to be; something like "remove the last dot and everything following it, assuming it exists and is not the first character of the filename".

请注意,此示例还暗示字符串作为输入和产出。由于大多数抽象需要 File 对象,如果它们也是输入和输出,那么它将更加清晰。

Note that this example also implies Strings as inputs and outputs. Since most of the abstraction requires File objects, it would be marginally clearer if those were the inputs and outputs as well.

这篇关于删除Java中的文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆