File file = new File(“d:/test.png”);
URLConnection connection = file.toURL().openConnection();
String mimeType = connection.getContentType();
}
结果:
| 文件 | 结果 | 结论 |
| — | — | — |
| test.png | image/png | ✔️ |
| test.doc | image/png | ✔️ |
结论:根据文件流中前几个字符判断。能够判断真实的文件类型,但是,这种方法的主要缺点是速度非常慢。
2.2 使用guessContentTypeFromName
public void test(){
File file = new File(“d:/test.png”);
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
}
结果:
| 文件 | 结果 | 结论 |
| — | — | — |
| test.png | image/png | ✔️ |
| test.doc | null | ❌ 具体参考下面的2.4 |
该方法利用内部的_FileNameMap_来判断MIME类型。
结论:根据文件扩展名判断。
2.3 使用guessContentTypeFromStream
public static void test() throws Exception {
FileInputStream inputFile = new FileInputStream(“d:/test.doc”);
String mimeType = URLConnection.guessContentTypeFromStream(new BufferedInputStream(inputFile));
System.out.println(mimeType);
}
结果:
| 文件 | 结果 | 结论 |
| — | — | — |
| test.png | image/png | ✔️ |
| test.doc | image/png | ✔️ |
结论:根据文件流中前几个字