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

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

当前回答

仅限文件名,其中还包括完整路径。不需要外部库,正则表达式等等

    public class MyClass {
    public static void main(String args[]) {
  
  
      String file  = "some/long/directory/blah.x.y.z.m.xml";

      System.out.println(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf(".")));
     //outputs blah.x.y.z.m
    }

}

其他回答

从相对路径或完整路径获取名称的最简单方法是使用

进口org.apache.commons.io.FilenameUtils; FilenameUtils.getBaseName (definitionFilePath)

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

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

如果您的项目使用Guava(14.0或更新版本),则可以使用Files.getNameWithoutExtension()。

(本质上与Apache Commons IO中的FilenameUtils.removeExtension()相同,正如投票最多的答案所表明的那样。只是想指出番石榴也会这样。就我个人而言,我不想在commons中添加依赖项——我觉得这有点过时了——就是因为这个原因。)

对于Kotlin来说,它现在很简单:

val fileNameStr = file.nameWithoutExtension

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

使用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());