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;
    }
}

打印效果图:

 

识别二维码关注个人微信公众号

本章完结,待续,欢迎转载!
 
本文说明:该文章属于原创,如需转载,请标明文章转载来源!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值