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

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

当前回答

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

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

其他回答

给定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中添加依赖项——我觉得这有点过时了——就是因为这个原因。)

请看下面的测试程序:

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
fileEntry.getName().substring(0, fileEntry.getName().lastIndexOf("."));
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("."));
    }