private static final Charset[] DEFAULT_CHARSETS;
static {
String[] names = {
"UTF-8",
"GBK",
"GB2312",
"GB18030",
"UTF-16BE",
"UTF-16LE",
"UTF-16",
"BIG5",
"UNICODE",
"US-ASCII"};
DEFAULT_CHARSETS = Convert.convert(Charset[].class, names);
}
/**
* 探测文件编码并根据文件编码读取文件内容
*
* @param file 文件
* @return
*/
public static Pair<String, Charset> readFileContentAutoDetectCharset(File file) {
if (!FileUtil.exist(file)) {
return Pair.of("", Charset.defaultCharset());
}
// 探测文件编码并根据文件编码读取文件
try (BufferedInputStream in = FileUtil.getInputStream(file)) {
final byte[] buffer = new byte[in.available()];
while (in.read(buffer) > -1) {
for (Charset charset : DEFAULT_CHARSETS) {
final CharsetDecoder decoder = charset.newDecoder();
try {
return Pair.of(decoder.decode(ByteBuffer.wrap(buffer)).toString(), charset);
} catch (CharacterCodingException ignore) {
}
}
}
} catch (IOException e) {
throw new BusinessException("文件读取错误!");
}
return Pair.of("", Charset.defaultCharset());
}
怎么优美的读取文件不乱码,首先我们每次读取一个文件是不知道它的编码格式是什么样的,而常规方式是读取文件按照utf-8,但也会有编码是GBK,那么有没有一个工具能够自己读取到文件是什么编码格式,然后按照这个格式不乱码的读取文件呢?
那么这篇文章应运而生