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

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

当前回答

com.google.common.io.Files

档案getNameWithoutExtension sourceFile。getName()。

能胜任一份工作吗

其他回答

以下是来自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基本函数。它负责处理有扩展名的字符串和没有扩展名的字符串(没有'。'字符)。多重'的情况。也有。

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);
}

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

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

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

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

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

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

fileEntry.getName().substring(0, fileEntry.getName().lastIndexOf("."));