SpringBoot 中检测文件编码格式

SpringBoot 中检测文件编码格式

引入相关依赖

<dependency>  
    <groupId>org.apache.commons</groupId>  
    <artifactId>commons-lang3</artifactId>  
    <version>3.6</version>  
</dependency>
<dependency>  
    <groupId>com.googlecode.juniversalchardet</groupId>  
    <artifactId>juniversalchardet</artifactId>  
    <version>1.0.3</version>  
</dependency>

工具类

import org.apache.commons.lang3.StringUtils;  
import org.mozilla.universalchardet.UniversalDetector;  
  
import java.io.*;  
import java.nio.file.Files;
  
public class FileUtils {  
    /**  
     * 自动检测文件的编码格式  
     *  
     * @param file 需要检测的文件  
     * @return encoding 编码格式,默认为 UTF-8  
     * @throws IOException  
     */    
     public static String detectFileEncoding(File file) throws IOException {  
        String encoding = null;  
        try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(file.toPath()))) {  
            UniversalDetector detector = new UniversalDetector(null);  
            byte[] buf = new byte[4096];  
            int len;  
            while ((len = bis.read(buf)) != -1 && !detector.isDone()) {  
                detector.handleData(buf, 0, len);  
            }  
            detector.dataEnd();  
            encoding = detector.getDetectedCharset();  
            detector.reset();  
        }  
        return !StringUtils.isBlank(encoding) ? encoding : "UTF-8";  
    }  
}

相关推荐

  1. SpringBoot 检测文件编码格式

    2024-05-11 19:00:05       37 阅读
  2. SpringBoot的yaml 与properties文件书写格式

    2024-05-11 19:00:05       37 阅读
  3. Notepad++批量更改文件编码格式文档格式

    2024-05-11 19:00:05       58 阅读
  4. excel wps编码格式转换

    2024-05-11 19:00:05       46 阅读
  5. Springboot 设置统一的返回格式

    2024-05-11 19:00:05       46 阅读
  6. 【Python】文件内容编码类型检测

    2024-05-11 19:00:05       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-11 19:00:05       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-11 19:00:05       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-11 19:00:05       87 阅读
  4. Python语言-面向对象

    2024-05-11 19:00:05       96 阅读

热门阅读

  1. SpringBoot 中 zip 文件解压工具类

    2024-05-11 19:00:05       32 阅读
  2. 【Python】如何训练模型并保存本地和加载模型

    2024-05-11 19:00:05       35 阅读
  3. 计算机答辩常见问题汇总(一)

    2024-05-11 19:00:05       34 阅读
  4. 蒙特卡洛求PI(抛点法)TypeScript实现

    2024-05-11 19:00:05       33 阅读
  5. 第十周笔记

    2024-05-11 19:00:05       36 阅读
  6. WHAT - npm和npx

    2024-05-11 19:00:05       31 阅读
  7. 【LeetCode】每日一题:2960. 统计已测试设备

    2024-05-11 19:00:05       30 阅读