Java 获取文件Content-Type四种方法

HTTP Content-Type在线工具

获取本地文件的Content-Type

<dependency>
    <groupId>net.sf.jmimemagic</groupId>
    <artifactId>jmimemagic</artifactId>
    <version>0.1.5</version>
</dependency>
import net.sf.jmimemagic.*;
import org.junit.Test;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.nio.file.Files;

public class GetContentType {
   //可通过  jpg、png、pdf、json、exe来验证输出结果
   @Test
   public void test() {
       List<String> paths = new ArrayList<String>();
       paths.add("D:\\img\\banner\\banner.png");
       paths.add("D:\\img\\banner\\1.jpg");
       paths.add("D:\\img\\banner\\1.json");//无文字
       paths.add("D:\\img\\banner\\2.json");//有文字
       paths.add("D:\\img\\banner\\1.txt");
       for (String pathname : paths) {
           try {
               Magic parser = new Magic();
               MagicMatch match = parser.getMagicMatch(new File(pathname), false);
               System.out.println("第一种Magic: " + match.getMimeType());
           } catch (MagicParseException e) {
               e.printStackTrace();
           } catch (MagicMatchNotFoundException e) {
               e.printStackTrace();
           } catch (MagicException e) {
               e.printStackTrace();
           }
           String contentType2 = new MimetypesFileTypeMap().getContentType(new File(pathname));
           System.out.println("第二种javax.activation: " + contentType2);
           try {
               String contentType3 = Files.probeContentType(new File(pathname).toPath());
               System.out.println("第三种java.nio: " + contentType3);
           } catch (IOException e) {
               e.printStackTrace();
           }
           FileNameMap fileNameMap = URLConnection.getFileNameMap();
           String contentType4 = fileNameMap.getContentTypeFor(pathname);
           System.out.println("第四种java.net: " + contentType4 + "\r\n");
       }
   }
}

输出结果

第一种Magic: image/png
第二种javax.activation: application/octet-stream
第三种java.nio: image/png
第四种java.net: image/png

第一种Magic: image/jpeg
第二种javax.activation: image/jpeg
第三种java.nio: image/jpeg
第四种java.net: image/jpeg

net.sf.jmimemagic.MagicMatchNotFoundException
	at net.sf.jmimemagic.Magic.getMagicMatch(Magic.java:370)
	at net.sf.jmimemagic.Magic.getMagicMatch(Magic.java:242)
	at GetContentType.test(GetContentType.java:29)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
第二种javax.activation: application/octet-stream
第三种java.nio: application/json
第四种java.net: null

第一种Magic: text/plain
第二种javax.activation: application/octet-stream
第三种java.nio: application/json
第四种java.net: null

net.sf.jmimemagic.MagicMatchNotFoundException
	at net.sf.jmimemagic.Magic.getMagicMatch(Magic.java:370)
	at net.sf.jmimemagic.Magic.getMagicMatch(Magic.java:242)
	at GetContentType.test(GetContentType.java:29)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
第二种javax.activation: text/plain
第三种java.nio: text/plain
第四种java.net: text/plain

总结

nio 和 net的方式区别不大。Magic的异常需要注意。javax.activation大部分只报application/octet-stream。
建议使用nio 与javax.activation 结合的方法。代码如下:

    @Test
    public void test2() {
        System.out.println(getContentType("D:\\img\\banner\\banner.png"));
        System.out.println(getContentType("D:\\img\\banner\\1.jpg"));
        System.out.println(getContentType("D:\\img\\banner\\1.txt"));
        System.out.println(getContentType("D:\\img\\banner\\1.json"));//无文字
        System.out.println(getContentType("D:\\img\\banner\\2.json"));//有文字
    }
    
    public String getContentType(String filePath) {
        //利用nio提供的类判断文件ContentType
        String content_type = null;
        try {
            content_type = Files.probeContentType(new File(filePath).toPath());
        } catch (IOException e) {
            System.out.println("Read File ContentType Error");
        }
        //若失败则调用另一个方法进行判断
        if (content_type == null) {
            content_type = new MimetypesFileTypeMap().getContentType(new File(filePath));
        }
        return content_type;
    }

输出结果

image/png
image/jpeg
text/plain
application/json
application/json

  • qq_43638135
    妲己再美究为妃: 博主没有想过自己接一些私活干吗?我现在还没毕业,但是我也确实听说外挂市场自动化游戏脚本市场挺火热的,并且报酬也很丰厚,但是具体的我也不是很清楚,求解答。 (1个月前 #47楼) 查看回复(2) 举报 回复
    22