明确一点,我并不是在寻找MIME类型。

假设我有以下输入:/path/to/file/foo.txt

我想要一种方法来分解这个输入,特别是扩展为.txt。在Java中有任何内置的方法来做到这一点吗?我希望避免编写自己的解析器。


当前回答

// Modified from EboMike's answer

String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));

扩展应该有“.txt”在它运行时。

其他回答

如果使用Guava库,可以求助于Files实用程序类。它有一个特定的方法getFileExtension()。例如:

String path = "c:/path/to/file/foo.txt";
String ext = Files.getFileExtension(path);
System.out.println(ext); //prints txt

另外,你也可以用类似的函数getNameWithoutExtension()获取文件名:

String filename = Files.getNameWithoutExtension(path);
System.out.println(filename); //prints foo

流利的方式:

fileExtension(String fileName) { 返回Optional.of (fileName.lastIndexOf(“。”))。过滤器(i-> i >= 0) .filter(i-> i > fileName.lastIndexOf(File.separator)) . map(文件名::substring) .orElse (" "); }

REGEX版本怎么样:

static final Pattern PATTERN = Pattern.compile("(.*)\\.(.*)");

Matcher m = PATTERN.matcher(path);
if (m.find()) {
    System.out.println("File path/name: " + m.group(1));
    System.out.println("Extention: " + m.group(2));
}

或者支持空扩展名:

static final Pattern PATTERN =
    Pattern.compile("((.*\\" + File.separator + ")?(.*)(\\.(.*)))|(.*\\" + File.separator + ")?(.*)");

class Separated {
    String path, name, ext;
}

Separated parsePath(String path) {
    Separated res = new Separated();
    Matcher m = PATTERN.matcher(path);
    if (m.find()) {
        if (m.group(1) != null) {
            res.path = m.group(2);
            res.name = m.group(3);
            res.ext = m.group(5);
        } else {
            res.path = m.group(6);
            res.name = m.group(7);
        }
    }
    return res;
}


Separated sp = parsePath("/root/docs/readme.txt");
System.out.println("path: " + sp.path);
System.out.println("name: " + sp.name);
System.out.println("Extention: " + sp.ext);

*nix的结果: 路径:/root/docs/ 名称:自述 延伸:三种

对于windows, parsePath("c:\windows\readme.txt"): 路径:c: \ windows \ 名称:自述 延伸:三种

如何(使用Java 1.5 RegEx):

    String[] split = fullFileName.split("\\.");
    String ext = split[split.length - 1];

我的肮脏和可能最小的使用String.replaceAll:

.replaceAll("^.*\\.(.*)$", "$1")

请注意,第一个*是贪婪的,所以它会尽可能地抓取大多数可能的字符,然后只剩下最后一个点和文件扩展名。