明确一点,我并不是在寻找MIME类型。
假设我有以下输入:/path/to/file/foo.txt
我想要一种方法来分解这个输入,特别是扩展为.txt。在Java中有任何内置的方法来做到这一点吗?我希望避免编写自己的解析器。
明确一点,我并不是在寻找MIME类型。
假设我有以下输入:/path/to/file/foo.txt
我想要一种方法来分解这个输入,特别是扩展为.txt。在Java中有任何内置的方法来做到这一点吗?我希望避免编写自己的解析器。
当前回答
private String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".");
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}
其他回答
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 \ 名称:自述 延伸:三种
// Modified from EboMike's answer
String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));
扩展应该有“.txt”在它运行时。
下面是Java 8的另一个一行程序。
String ext = Arrays.stream(fileName.split("\\.")).reduce((a,b) -> b).orElse(null)
其工作原理如下:
使用"."将字符串拆分为字符串数组。 将数组转换为流 使用reduce获取流的最后一个元素,即文件扩展名
如果你在项目中使用Spring框架,那么你可以使用StringUtils
import org.springframework.util.StringUtils;
StringUtils.getFilenameExtension("YourFileName")
String extension = com.google.common.io.Files.getFileExtension("fileName.jpg");