Java获取文件获取文件ContentType案例案例
主要介绍了Java获取文件ContentType案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
源码如下:源码如下:
package com.oysept;
import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.activation.MimetypesFileTypeMap;
/**
* Java获取文件ContentType
* @author ouyangjun
*/
public class ContentTypeUtils {
public static void main(String[] args) {
// 文件路径
String fileUrl = "C:\Users\admin\Desktop\tttt.rar";
// 方式一
getContentTypeByLocal(fileUrl);
// 方式二,推荐使用
getContentType(fileUrl);
// 方式三
getContentTypeByType(fileUrl);
}
/**
* 方式一
* 该方式只支持本地文件,有时候会存在获取为null的情况
* @param fileUrl
*/
public static String getContentTypeByLocal(String fileUrl) {
String contentType = null;
Path path = Paths.get(fileUrl);
try {
contentType = Files.probeContentType(path);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("getContentTypeByLocal, File ContentType is : " + contentType);
return contentType;
}
/**
* 方式二
* 该方式支持本地文件,也支持http/https远程文件
* @param fileUrl
*/
public static String getContentType(String fileUrl) {
String contentType = null;
try {
contentType = new MimetypesFileTypeMap().getContentType(new File(fileUrl));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("getContentType, File ContentType is : " + contentType);
return contentType;
}
/**
* 方式三
* @param fileUrl,有时候会存在获取为null的情况
*/
public static String getContentTypeByType(String fileUrl) {
String contentType = null;
try {
FileNameMap fileNameMap = URLConnection.getFileNameMap();
contentType = fileNameMap.getContentTypeFor(fileUrl);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("getContentTypeByType, File ContentType is : " + contentType);
return contentType;
}
}
打印效果图:
补充知识:补充知识:ImageTypeUtil工具类:工具类:Java获取获取URL对应的文件类型及其后缀对应的文件类型及其后缀
Java获取URL对应的文件类型及其后缀的主流方法有三种:
1、根据文件头部数据来判断。、根据文件头部数据来判断。
通常需要先下载再判断,但是如果想要在下载的时候确定文件后缀,就做不到了,而且获取的文件类型不是很准确。
评论0