【解决】字节输入流汉语乱码问题
1.确保txt文档为utf-8格式;
2.实例化FileInputStream类对象
3.声明一个byte类型数组,用于缓存非汉字字节
4.测试得到一个utf-8汉字字符为三个字节,并且每个存入byte类型数组中时,都得到负数
5.做个判断,当遇到汉字时,就定义一个byte类型数组,长度为3的,用于缓存汉字字节。
6.再声明一个count为长度为3的数组下标
7.遍历赋值,再打印出来
8.关闭资源
public class Test {
public static void main(String[] args) {
File file1 = new File("e:\\chao.txt");
try {
file1.createNewFile();
// 查看内容
FileInputStream file = new FileInputStream(file1);
byte[] arr = new byte[1];
while (file.read(arr) != -1) {
if (arr[0] < 0) { // 当值少于0
int count = 0;
byte[] arr2 = new byte[3];
while (true) {
arr2[count++] = arr[0];
if (count == 3)
break;
else
file.read(arr);
}
System.out.print(new String(arr2));
} else // 不少于0
System.out.print(arr);
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}
// 字节输入流
}
}