在Java中识别文件类型 [英] Identifying file type in Java

查看:301
本文介绍了在Java中识别文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我查一下上传文件的类型。
我想区分excel类型和csv。

Please help me to find out the type of the file which is being uploaded. I wanted to distinguish between excel type and csv.

MIMEType为这两个文件返回相同的内容。请帮助。

MIMEType returns same for both of these file. Please help.

推荐答案

我使用 Apache Tika 使用魔术字节模式和globbing提示(文件扩展名)标识文件类型以检测MIME类型。它还支持额外的文件内容解析(我并不真正使用)。

I use Apache Tika which identifies the filetype using magic byte patterns and globbing hints (the file extension) to detect the MIME type. It also supports additional parsing of file contents (which I don't really use).

这是一个关于Tika如何用于检测文件的快速而肮脏的示例键入而不对文件执行任何其他解析:

Here is a quick and dirty example on how Tika can be used to detect the file type without performing any additional parsing on the file:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;

import org.apache.tika.metadata.HttpHeaders;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaMetadataKeys;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.xml.sax.helpers.DefaultHandler;

public class Detector {

    public static void main(String[] args) throws Exception {
        File file = new File("/pats/to/file.xls");

        AutoDetectParser parser = new AutoDetectParser();
        parser.setParsers(new HashMap<MediaType, Parser>());

        Metadata metadata = new Metadata();
        metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName());

        InputStream stream = new FileInputStream(file);
        parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());
        stream.close();

        String mimeType = metadata.get(HttpHeaders.CONTENT_TYPE);
        System.out.println(mimeType);
    }

}

这篇关于在Java中识别文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆