java用字节数组解决FileInputStream读取汉字出现乱码问题
作者:深入技术了解原理
这篇文章主要介绍了java用字节数组解决FileInputStream读取汉字出现乱码问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
用字节数组解决FileInputStream读取汉字出现乱码
package hanjia;
import java.io.*;
//用“字节数组”方式读取文本文件内容,然后利用String(byte[] bytes)
//或String(byte[] bytes, int offset, int length) 构造新字符串来输出。
//解决思路:先用较大的字节数组读取文本文件内容,将调用String类构造方法将字节数组内容组合成有意义的汉字
class hanjia {
public static void main(String args[]) throws IOException {
FileInputStream infile = new FileInputStream("D:/KuGou/f.txt");
try {
byte[] b = new byte[128];// 定义一个字节数组
int i = infile.read(b);// 读取数据存放到字节数组中,read()返回值-1表示结束
while (i != -1) {// 读指针到达输出流尾部时结束
System.out.print(new String(b, 0, i));//从开头到结束将字节数组内容转换为字符串,并输出
i = infile.read(b);// 读取后续数据存放到字节数组中
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
infile.close();// 关闭输入流
}
}
}

解决FileInputStream读取ANSI格式txt中文乱码
GBK中文转为byte后以负数开头,正常来说为连续两个负数,生僻字可能为一个负数和一个整数,所以需要特殊处理一下
注:utf-8的txt一个中文占三个byte数组,故此方法不适用
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class FileInputStreamTest03 {
public static void main(String[] args) {
// test
String s = "中c国Dh丄";
byte[] bs = new byte[10];
try {
bs = s.getBytes("GBK");
System.out.println(Arrays.toString(bs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String s2 = null;
try {
s2 = new String(bs, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(s2);
// main
FileInputStream fp = null;
try {
fp = new FileInputStream("C:\\Users\\dell\\Documents\\a代码备份\\python\\爬虫\\bilibili\\list.txt");
byte[] b = new byte[10];
int num;
while ((num = fp.read(b)) != -1){
int pos = 0; // 记录负值个数,中文GBK为两个负值
for (byte b1 : b) {
if (b1 < 0){
pos++;
}
}
// System.out.println(Arrays.toString(b));
if (pos%2 != 0 && b[b.length-1] < 0){
int nextValue=fp.read();
int size = b.length;
int nextLen=size+1;
//字节数组扩容一位
b = Arrays.copyOf(b,nextLen);
b[size]= (byte) nextValue;
String content=new String(b, 0, nextLen, "GBK");
System.out.print(content);
} else {
System.out.print(new String(b, 0, num, "GBK"));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fp != null){
try {
fp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
