在Java中很多方式可以確定文件的類型,所以我們可以輕鬆的確定文件的MIMEType。在這些方式中大多數都是通過讀取文件的內容來確定的,但是有時候本地並沒有這個文件,或者我不想讀取這個文件的文件流,這時候我希望通過文件名中的後綴來確定。我找到了以下三種方法。
方法一:Files.probeContentType()
優缺點
- 優點
-
- 無需第三方依賴
- 缺點
-
- 受操作系統影響,在不同的操作系統下返回結果不同(返回null)
用法
示例代碼
Path path1 = Paths.get("123.jpg");
Path path2 = Paths.get("123.mp4");
String contentType1 = Files.probeContentType(path1);
String contentType2 = Files.probeContentType(path2);
System.out.println(contentType1);
System.out.println(contentType2);
輸出結果
image/jpeg
video/mp4
方法二:URLConnection.guessContentTypeFromName()
優缺點
- 優點
-
- 無需第三方依賴
- 缺點
-
- 支持的文件格式較少,不支持主流視頻音頻格式等(返回null)
用法
示例代碼
String contentType1 = URLConnection.guessContentTypeFromName("123.jpg");
String contentType2 = URLConnection.guessContentTypeFromName("123.mp4");
System.out.println(contentType1);
System.out.println(contentType2);
輸出結果
image/jpeg
null
方法三:使用simplemagic工具包
優缺點
- 優點
-
- 不受操作系統影響,支持格式全面
- 缺點
-
- 需要引入第三方依賴包
用法
引入依賴(以maven爲例)
<dependency>
<groupId>com.j256.simplemagic</groupId>
<artifactId>simplemagic</artifactId>
<version>1.16</version>
</dependency>
示例代碼
//注意:如果是不支持的格式,返回的ContentInfo爲null,調用getMimeType()時會導致空指針異常
ContentInfo info1 = ContentInfoUtil.findExtensionMatch("123.jpg");
ContentInfo info2 = ContentInfoUtil.findExtensionMatch("123.mp4");
String contentType1 = info1.getMimeType();
String contentType2 = info2.getMimeType();
System.out.println(contentType1);
System.out.println(contentType2);
輸出結果
image/jpeg
video/mp4