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

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

当前回答

你可以使用java split函数从扩展名中分离文件名,如果你确定文件名中只有一个用于扩展名的点。

文件文件名=新文件('test.txt'); File.getName () .split(“[]”);

因此拆分[0]将返回test拆分[1]将返回txt

其他回答

你可以使用java split函数从扩展名中分离文件名,如果你确定文件名中只有一个用于扩展名的点。

文件文件名=新文件('test.txt'); File.getName () .split(“[]”);

因此拆分[0]将返回test拆分[1]将返回txt

public static String getFileExtension(String fileName) {
        if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static String getBaseFileName(String fileName) {
        if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
        return fileName.substring(0,fileName.lastIndexOf("."));
    }

试试下面的代码。使用核心Java基本函数。它负责处理有扩展名的字符串和没有扩展名的字符串(没有'。'字符)。多重'的情况。也有。

String str = "filename.xml";
if (!str.contains(".")) 
    System.out.println("File Name=" + str); 
else {
    str = str.substring(0, str.lastIndexOf("."));
    // Because extension is always after the last '.'
    System.out.println("File Name=" + str);
}

您可以调整它来处理空字符串。

你可以用“。”来分割它,在索引0上是文件名,在索引1上是扩展名,但是我倾向于使用apache.commons-io中的FileNameUtils,就像在第一篇文章中提到的那样。它不需要被移除,但足够:

String fileName = FilenameUtils.getBaseName("test.xml");

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

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