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

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

当前回答

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

val fileNameStr = file.nameWithoutExtension

其他回答

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

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

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

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

以下是来自https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java的参考资料

/**
 * Gets the base name, without extension, of given file name.
 * <p/>
 * e.g. getBaseName("file.txt") will return "file"
 *
 * @param fileName
 * @return the base name
 */
public static String getBaseName(String fileName) {
    int index = fileName.lastIndexOf('.');
    if (index == -1) {
        return fileName;
    } else {
        return fileName.substring(0, index);
    }
}

你可以使用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("."));
    }