Java中识别文件类型

发布于 2024-10-10 02:27:15 字数 81 浏览 0 评论 0原文

请帮我找出正在上传的文件的类型。 我想区分excel类型和csv类型。

MIMEType 对于这两个文件返回相同的结果。请帮忙。

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 returns same for both of these file. Please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浅唱々樱花落 2024-10-17 02:27:15

我使用 Apache Tika 它使用魔术字节模式和通配提示(文件扩展名)来识别文件类型来检测 MIME 类型。它还支持对文件内容的额外解析(我并没有真正使用)。

下面是一个快速而简单的示例,说明如何使用 Tika 来检测文件类型,而不需要对文件执行任何额外的解析:

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

}

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).

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

}
小鸟爱天空丶 2024-10-17 02:27:15

我希望这会有所帮助。取自一个不是我的例子:

import javax.activation.MimetypesFileTypeMap;
import java.io.File;

class GetMimeType {
  public static void main(String args[]) {
    File f = new File("test.gif");
    System.out.println("Mime Type of " + f.getName() + " is " +
                         new MimetypesFileTypeMap().getContentType(f));
    // expected output :
    // "Mime Type of test.gif is image/gif"
  }

}

对于 excel 和 csv 类型来说也是如此。未测试。

I hope this will help. Taken from an example not from mine:

import javax.activation.MimetypesFileTypeMap;
import java.io.File;

class GetMimeType {
  public static void main(String args[]) {
    File f = new File("test.gif");
    System.out.println("Mime Type of " + f.getName() + " is " +
                         new MimetypesFileTypeMap().getContentType(f));
    // expected output :
    // "Mime Type of test.gif is image/gif"
  }

}

Same may be true for excel and csv types. Not tested.

蓝戈者 2024-10-17 02:27:15

我想出了一种更便宜的方法来使用 java.nio.file.Files

public String getContentType(File file) throws IOException {
        return Files.probeContentType(file.toPath());
}

- 或 -

public String getContentType(Path filePath) throws IOException {
        return Files.probeContentType(filePath);
}

希望有帮助。

干杯。

I figured out a cheaper way of doing this with java.nio.file.Files

public String getContentType(File file) throws IOException {
        return Files.probeContentType(file.toPath());
}

- or -

public String getContentType(Path filePath) throws IOException {
        return Files.probeContentType(filePath);
}

Hope that helps.

Cheers.

半步萧音过轻尘 2024-10-17 02:27:15

更好的方法 不使用 javax.activation.*

 URLConnection.guessContentTypeFromName(f.getAbsolutePath()));

A better way without using javax.activation.*:

 URLConnection.guessContentTypeFromName(f.getAbsolutePath()));
相思碎 2024-10-17 02:27:15

如果您已经在使用 Spring,这适用于 csv 和 excel:


import org.springframework.mail.javamail.ConfigurableMimeFileTypeMap;

import javax.activation.FileTypeMap;
import java.io.IOException;

public class ContentTypeResolver {

    private FileTypeMap fileTypeMap;

    public ContentTypeResolver() {
        fileTypeMap = new ConfigurableMimeFileTypeMap();
    }

    public String getContentType(String fileName) throws IOException {
        if (fileName == null) {
            return null;
        }
        return fileTypeMap.getContentType(fileName.toLowerCase());
    }

}

或者使用 javax.activation 您可以更新 mime.types 文件。

If you are already using Spring this works for csv and excel:


import org.springframework.mail.javamail.ConfigurableMimeFileTypeMap;

import javax.activation.FileTypeMap;
import java.io.IOException;

public class ContentTypeResolver {

    private FileTypeMap fileTypeMap;

    public ContentTypeResolver() {
        fileTypeMap = new ConfigurableMimeFileTypeMap();
    }

    public String getContentType(String fileName) throws IOException {
        if (fileName == null) {
            return null;
        }
        return fileTypeMap.getContentType(fileName.toLowerCase());
    }

}

or with javax.activation you can update the mime.types file.

哽咽笑 2024-10-17 02:27:15

CSV 将以文本开头,Excel 类型很可能是二进制。

然而,最简单的方法是尝试使用 POI 加载 Excel 文档。如果失败,请尝试将文件加载为 CSV,如果失败,则可能不是两种类型。

The CSV will start with text and the excel type is most likely binary.

However the simplest approach is to try to load the excel document using POI. If this fails try to load the file as a CSV, if that fails its possibly neither type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文