java 字节数组 字符串 编码_java判断byte[]数组的原字符串编码类型【转载】

在做项目之间的字符数组传递时一直未找到一种简洁有效的写法,来实现文件内容的字符集转换,以下内容为转载内容,实现方式简洁,特此转载:

》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》

最近做html脚本导入库中,读取时总会有乱码的情况。找到一些方法乱码转为正确字符串输出。

参考原文:

https://blog.csdn.net/ajaxhu/article/details/12446917

com.googlecode.juniversalchardet

juniversalchardet

1.0.3

48304ba5e6f9fe08f3fa1abda7d326ab.png

@Slf4j

public class Test {

@Test

public void encode() throws IOException {

String file = "C:\\Users\\Victory-x\\Desktop\\code.html";

byte[] bytes = file2byte(file);

//编码判断

String encoding = GetByteEncode.getEncoding(bytes);

System.out.println("字符编码是:" + encoding);

System.out.println("原乱码输出:" + new String(bytes));

System.out.println("//***********************//");

System.out.println("根据文件编码输出:" + new String(bytes, encoding));

}

public static byte[] file2byte(String filePath) throws IOException {

byte[] buffer = null;

try {

File file = new File(filePath);

FileInputStream fis = new FileInputStream(file);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

byte[] b = new byte[1024];

int n;

while ((n = fis.read(b)) != -1) {

bos.write(b, 0, n);

}

fis.close();

bos.close();

buffer = bos.toByteArray();

} catch (FileNotFoundException e) {

e.printStackTrace();

}

return buffer;

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

GetByteEncode:

48304ba5e6f9fe08f3fa1abda7d326ab.png

import lombok.extern.slf4j.Slf4j;

import org.mozilla.universalchardet.UniversalDetector;

/**

* 获取文件编码类型

*

* @author XSL

* @version Id: GetByteEncode.java, V 1.0 2018/11/30 10:03 XSL Exp $$

*/

@Slf4j

public class GetByteEncode {

/**

* 获取文件编码类型

*

* @param bytes 文件bytes数组

* @return 编码类型

*/

public static String getEncoding(byte[] bytes) {

String defaultEncoding = "UTF-8";

UniversalDetector detector = new UniversalDetector(null);

detector.handleData(bytes, 0, bytes.length);

detector.dataEnd();

String encoding = detector.getDetectedCharset();

detector.reset();

log.info("字符编码是:{}", encoding);

if (encoding == null) {

encoding = defaultEncoding;

}

return encoding;

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

其它方法乱码转换,原文:

http://daikainan.iteye.com/blog/1439322

《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值