谁能告诉我如何在没有扩展名的情况下获取文件名? 例子:

fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";

当前回答

这是根据我的喜好排列的综合清单。

使用apache commons

import org.apache.commons.io.FilenameUtils;

String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
                          
                           OR

String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

使用谷歌番石榴(如果你已经在使用)

import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);

Files.getNameWithoutExtension

或者使用Core Java

1)

String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character.
    fileName = fileName.substring(0, pos);
}
if (fileName.indexOf(".") > 0) {
   return fileName.substring(0, fileName.lastIndexOf("."));
} else {
   return fileName;
}
private static final Pattern ext = Pattern.compile("(?<=.)\\.[^.]+$");

public static String getFileNameWithoutExtension(File file) {
    return ext.matcher(file.getName()).replaceAll("");
}

生命之光接口

import com.liferay.portal.kernel.util.FileUtil; 
String fileName = FileUtil.stripExtension(file.getName());

其他回答

给定String文件名,你可以这样做:

String filename = "test.xml";
filename.substring(0, filename.lastIndexOf("."));   // Output: test
filename.split("\\.")[0];   // Output: test

请看下面的测试程序:

public class javatemp {
    static String stripExtension (String str) {
        // Handle null case specially.

        if (str == null) return null;

        // Get position of last '.'.

        int pos = str.lastIndexOf(".");

        // If there wasn't any '.' just return the string as is.

        if (pos == -1) return str;

        // Otherwise return the string, up to the dot.

        return str.substring(0, pos);
    }

    public static void main(String[] args) {
        System.out.println ("test.xml   -> " + stripExtension ("test.xml"));
        System.out.println ("test.2.xml -> " + stripExtension ("test.2.xml"));
        System.out.println ("test       -> " + stripExtension ("test"));
        System.out.println ("test.      -> " + stripExtension ("test."));
    }
}

输出:

test.xml   -> test
test.2.xml -> test.2
test       -> test
test.      -> test

com.google.common.io.Files

档案getNameWithoutExtension sourceFile。getName()。

能胜任一份工作吗

流利的方式:

public static String fileNameWithOutExt (String fileName) {
    return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
            .filter(i-> i > fileName.lastIndexOf(File.separator))
            .map(i-> fileName.substring(0, i)).orElse(fileName);
}

如果你像我一样,宁愿使用一些库代码,他们可能已经考虑了所有的特殊情况,比如如果你在路径中传递null或圆点,而不是在文件名中,会发生什么,你可以使用以下方法:

import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);