Remove filename extension in Java

后端 未结 10 2229
你的背包
你的背包 2020-12-09 08:48

(Without including any external libraries.)

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

10条回答
  •  攒了一身酷
    2020-12-09 09:44

    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".

    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.

提交回复
热议问题