解决读取SQL脚本乱码问题(仅仅支持GBK、UTF-8、UTF8-bom)

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author: guanglai.zhou
 * @date: 2021/3/18 11:09
 * @description: sql脚本读取 通常sql脚本会涉及到编码问题 当前工具类可以用于读取GBK、UTF-8、UTF8-bom格式的脚本
 * @version: 1.0
 */
public class SqlScriptReadUtils {
    /**
     * 基于GBK乱码几乎都包含有一个�字符 所有首先尝试通过UTF-8读取文件 如果包含�字符 则认为编码错误 按照GBK读取
     */
    public static String[] unReg = new String[]{"�", "Э", "ҵ", "ع"};
    /**
     * UTF8-bom格式文件用UTF-8读取的话 会在前面包含一个肉眼看不见的字符 导致读取的内容无法直接当做SQL执行
     */
    public static final String BOM_EMPTY_CHAR = "\uFEFF";

    /**
     * 读取脚本 支持格式为GBK、UTF-8、UTF8-bom格式的脚本
     *
     * @param file 文件资源
     * @return
     */
    public static String readFile(File file) {
        try {
            String sqlContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
            if (isGBK(sqlContent)) {
                sqlContent = FileUtils.readFileToString(file, "GBK");
            }
            // 去掉无用字符 此处能够去掉UTF-8 BOM中的无用字符
            sqlContent = sqlContent.trim();
            sqlContent = StringUtils.strip(sqlContent, BOM_EMPTY_CHAR);
            return sqlContent;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 通过UTF_8读取 如果包含有乱码 则为GBK
     *
     * @param content
     * @return
     */
    private static boolean isGBK(String content) {
        for (String un : unReg) {
            if (content.contains(un)) {
                return true;
            }
        }
        return false;
    }
}

需要依赖的jar包

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lang20150928

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值