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>