Java文件格式类型判断的方法详解

 更新时间:2026年06月11日 08:50:41   作者:西凉的悲伤  
本文介绍了两种通过URL下载文件并并识别其文件类型的方法,,方式一利用通过文件魔数识别方式二通过ApacheTika库识别并旨在提供更可靠的文件类型判断识别方法,需要的朋友可以参考下

前言

如果一个 url

例如 : https://i-blog.csdnimg.cn/direct/4b54f5f678bb404f8f92007792e46592.png

上面的链接我们可以轻松的通过 后缀 .png 判断它的文件类型,但是很多时候有的 url 链接是不带这种后缀的,并且有时候即使 url 带了.png 后缀,它下载下来也不一定是 png 文件 ,所以需要下载文件后根据文件字节码去判断。

本文通过两种方式来判断文件类型。

方式一:通过文件url 获取到文件字节数组,通过文件魔数(Magic Number)识别文件类型,比只靠文件后缀识别更可靠。

方式一:通过 tika 库来识别文件类型

方式一

1.依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.3.29</version>
        </dependency>

2.枚举类和工具类

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 文件类型枚举
 *
 */
@Getter
@AllArgsConstructor
public enum FileTypeEnum {

    /**
     * JEPG.
     */
    JPEG("FFD8FF", "image/jpg"),


    /**
     * PNG.
     */
    PNG("89504E47", "image/png"),

    /**
     * Adobe Acrobat.
     */
    PDF("255044462D312E", "application/pdf"),

    OTHER("OTHER", "OTHER");

    private String value;

    private String contentType;
}
import com.hai.tang.model.FileTypeEnum;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

public class FileTypeUtils {

    /**
     * 从文件 url 下载获取文件字节数组
     * @param url 文件url
     * @turn FileTypeEnum 文件类型枚举
     */
    public static ResponseEntity<byte[]> downloadFile(final String url) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 设置超时时间为5秒
        requestFactory.setReadTimeout(5000);
        requestFactory.setConnectTimeout(60000);

        RestTemplate restTemplate = new RestTemplate(requestFactory);
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
        return entity;
    }

    /**
     * 从文件字节数组中前16比特获取文件类型
	 * @param bytes 文件字节数组
	 * @turn FileTypeEnum 文件类型枚举
     */
    public static FileTypeEnum getFileType(byte[] bytes) {
        int length = Math.min(bytes.length, 16);
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; i++) {
            sb.append(String.format("%02X", bytes[i]));
        }
        String fileHead = sb.toString();
        for (FileTypeEnum type : FileTypeEnum.values()) {
            if (fileHead.startsWith(type.getValue())) {
                return type;
            }
        }
        return FileTypeEnum.OTHER;
    }
    
     /**
     * 将 base64 文件保存到本地
     *
     * @param fileBase64 文件base64
     * @param fileType 文件类型 FileTypeEnum 里的 contentType
     * @param outPath 文件要保存到的本地路径,如: C:\Users\haitang\Desktop
     *
     */
    public static void save(String fileBase64, String fileType, String outPath) throws IOException {
        //将 base64 文件 转为 字节数组
        byte[] bytes = Base64.getDecoder().decode(fileBase64);
        String suffix = fileType.split("/")[1];
        DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
        String time = LocalDateTime.now().format(f);
        String fileName = time + "." + suffix;
        //文件保存到本地
        Files.write(Paths.get(outPath + File.separator + fileName), bytes);
    }

}

3.测试

用于测试的三个 png、jpg、pdf 文件链接

https://i-blog.csdnimg.cn/direct/4b54f5f678bb404f8f92007792e46592.png
https://pic3.zhimg.com/v2-e88c84efc46685275936b278784c0d16_1440w.jpg
https://www.kkoworld.com/kitablar/Nikolas_Sparks_Sevimli_Con_eng.pdf

测试代码如下,通过工具类下载 url 链接为字节数组然后打印文件类型

import com.hai.tang.util.FileTypeUtils;
import org.springframework.http.ResponseEntity;  

public class MainServer {
	public static void main(String[] args) throws Exception {
        String fileUrl = "https://i-blog.csdnimg.cn/direct/4b54f5f678bb404f8f92007792e46592.png";
        ResponseEntity<byte[]> entity = FileTypeUtils.downloadFile(fileUrl);
        if (entity.hasBody() && null != entity.getBody()) {
            //获取文件类型 image/jpg 或 image/png 或 application/pdf
            String attachmentType = FileTypeUtils.getFileType(entity.getBody()).getContentType();
            System.out.println(attachmentType);

            //将 entity.getBody() 即文件字节数组 转化为 base64 编码的字符串(可用于存储到数据库)
            String attachmentBase64Stream = DatatypeConverter.printBase64Binary(entity.getBody());
            // base64 编码的文件字符串 输出到 C:\Users\haitang\Desktop 保存
            FileTypeUtils.save(attachmentBase64Stream,attachmentType,"C:\\Users\\haitang\\Desktop");
        }
    }
}

方式二

使用 Apache Tika 来进行文件类型识别,Apache Tika 是一个非常强大的“文件内容分析工具”。

很多企业系统会用它做:

  • 文件类型识别
  • MIME识别
  • 文件内容提取
  • Office/PDF解析
  • 文本抽取
  • 元数据读取
  • 文件安全检测前置处理

Apache Tika gitHubD地址

1.依赖

        <dependency>
            <groupId>org.apache.tika</groupId>
            <artifactId>tika-core</artifactId>
            <version>2.9.4</version>
            <scope>compile</scope>
        </dependency>

2.枚举类

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * 文件类型枚举
 */
@Getter
@AllArgsConstructor
public enum FileTypeEnum {

    /**
     * jpg.
     */
    JPEG("image/jpeg"),


    /**
     * png.
     */
    PNG("image/png"),

    /**
     * pdf
     */
    PDF("application/pdf"),

    /**
     * zip
     */
    ZIP("application/zip"),

    /**
     * xlsx
     */
    XLSX("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),

    /**
     * xls
     */
    xls("application/vnd.ms-excel"),

    /**
     * mp4
     */
    MP4("video/mp4"),

    /**
     * mp3
     */
    MP3("audio/mpeg"),

    /**
     * pptx
     */
    PPTX("application/vnd.openxmlformats-officedocument.presentationml.presentation"),

    /**
     * ppt
     */
    PPT("application/vnd.ms-powerpoint"),

    /**
     * docx
     */
    DOCX("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),

    /**
     * doc
     */
    DOC("application/msword"),

    /**
     * txt
     */
    TXT("text/plain"),

    /**
     * RAR4
     */
    RAR4("application/x-rar-compressed"),

    /**
     * RAR5
     */
    RAR5("application/application/vnd.rar"),

    OTHER("OTHER");

    private String value;

}

3.使用

(1)通过 url 判断文件类型

import com.hai.tang.model.FileTypeEnum;
import org.apache.tika.Tika;

import java.io.InputStream;
import java.net.URL;

public class MainServer {
    public static void main(String[] args) throws Exception {
       String fileUrl = "https://i-blog.csdnimg.cn/direct/4b54f5f678bb404f8f92007792e46592.png";

        Tika tika = new Tika();

        try (InputStream in = new URL(fileUrl).openStream()) {
            String mimeType = tika.detect(in);
            System.out.println(mimeType);

            if (FileTypeEnum.PNG.getValue().equals(mimeType)) {
                System.out.println("是PNG文件");
            }
        }
    }
}

(2)读取本地文件判断

import com.hai.tang.model.FileTypeEnum;
import org.apache.tika.Tika;
import java.io.File;

public class MainServer {
    public static void main(String[] args) throws Exception {
        File file = new File("C:\\Users\\haitang\\Downloads\\chromedriver-win64.zip");

        Tika tika = new Tika();
        String mimeType = tika.detect(file);
        System.out.println(mimeType);
        if (FileTypeEnum.ZIP.getValue().equals(mimeType)) {
            System.out.println("是ZIP文件");
        }
    }


}

(3)通过文件流读取

import com.hai.tang.model.FileTypeEnum;
import org.apache.tika.Tika;

import java.io.FileInputStream;
import java.io.InputStream;

public class MainServer {
    public static void main(String[] args) throws Exception {
                Tika tika = new Tika();

        try (InputStream in = new FileInputStream("C:\\Users\\haitang\\Downloads\\chromedriver-win64.zip")) {
            //文件流
            String mimeType = tika.detect(in);

            if (FileTypeEnum.ZIP.getValue().equals(mimeType)) {
                System.out.println("是ZIP文件");
            }
        }

    }
}

以上就是Java文件格式类型判断的方法详解的详细内容,更多关于Java文件格式类型判断的资料请关注脚本之家其它相关文章!

相关文章

  • 如何导入spring源码到IDEA

    如何导入spring源码到IDEA

    这篇文章主要介绍了如何导入spring源码到IDEA,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • 使用Mybatis遇到的there is no getter异常

    使用Mybatis遇到的there is no getter异常

    这篇文章主要介绍了使用Mybatis遇到的there is no getter异常,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • 解决IDEA maven 项目修改代码不生效,mvn clean、install后才生效

    解决IDEA maven 项目修改代码不生效,mvn clean、install后才生效

    这篇文章主要介绍了解决IDEA maven 项目修改代码不生效,mvn clean、install后才生效的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • springboot中请求地址转发的两种方案

    springboot中请求地址转发的两种方案

    在开发过程中,我们经常需要将请求从一个服务转发到另一个服务,以实现不同服务之间的协作,本文主要介绍了springboot中请求地址转发的两种方案,感兴趣的可以了解一下
    2023-11-11
  • MyBatis-Plus 全面介绍与Spring Boot 集成最佳实践

    MyBatis-Plus 全面介绍与Spring Boot 集成最佳实践

    MyBatis-Plus是MyBatis的增强工具,提供了通用CRUD、分页、条件构造器等功能,简化了开发,减少重复SQL编写,它支持多种主键生成策略,内置乐观锁和逻辑删除,且兼容MyBatis原有代码,本文介绍MyBatis-Plus全面介绍与Spring Boot 集成最佳实践,感兴趣的朋友一起看看吧
    2025-12-12
  • idea中写sql语句没有提示字段的问题

    idea中写sql语句没有提示字段的问题

    在IDEA中编写SQL时如果没有字段提示,通常是因为没有设置注入语言,解决方法是通过快捷键Alt+Enter选择“注入语言或引用”,然后选择相应的数据库(如MySQL),之后重新输入SQL语句即可,此方法可以有效解决IDEA中SQL语句提示问题,提高开发效率
    2024-09-09
  • 初识Java一些常见的数据类型

    初识Java一些常见的数据类型

    这篇文章主要介绍Java一些常见的数据类型,Java是一种优秀的程序设计语言,它具有令人赏心悦目的语法和易于理解的语义,下面文章小编就来简单介绍为什么说Java是最好的语言并且介绍它的各种常见类型,需要的朋友可以参考一下
    2021-10-10
  • JAVA CountDownLatch(倒计时计数器)用法实例

    JAVA CountDownLatch(倒计时计数器)用法实例

    这篇文章主要介绍了JAVA CountDownLatch(倒计时计数器)用法实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • JAVA实现KMP算法理论和示例代码

    JAVA实现KMP算法理论和示例代码

    本文从理论到代码讲解了JAVA对KMP算法的实现,大家可以参考一下
    2013-11-11
  • Java使用Spire.Presentation在PowerPoint中添加或删除表格行与列

    Java使用Spire.Presentation在PowerPoint中添加或删除表格行与列

    在日常开发中,Java 开发者常需自动化生成报告PPT,手动编辑PowerPoint 表格行与列效率低下,尤其批量操作时易出错,Spire.Presentation for Java 库提供高效解决方案,本文分享实用代码与步骤,助你快速上手,需要的朋友可以参考下
    2026-02-02

最新评论