如何使用文件二进制内容查找文件mime-type / content-type?

时间:2015-11-18 15:17:34

标签: java file mime-types content-type

我的文件内容目前为byte[],我想知道它的mime-type / content-type标头。

问题在于,我在网上看到很多例子来查找它,但只有当文件确实存在时才会找到。

如何仅通过此byte[]获取此信息。

我测试的大部分代码都是:

File f = new File("gumby.gif");
System.out.println("Mime Type: " + new MimetypesFileTypeMap().getContentType(f));

编辑1: 这段代码给了我一个错误的结果:application/octet-stream

有没有办法在不创建文件的情况下获取此信息?

编辑2: 我试过这段代码:

public static void main(String[] args) throws Exception{

    Tika tika = new Tika();     
    byte[] content = readFile().getBytes();     
    System.out.println(tika.detect(content));
}    

private static String readFile() throws Exception{
    BufferedReader br = new BufferedReader(new FileReader("c:\\pic.jpg"));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        String everything = sb.toString();
        return everything;
    } finally {
        br.close();
    }       
}

并且它始终返回application/octet-stream,是因为我使用byte[]作为参数吗?

0 个答案:

没有答案