【解决】字节输入流汉语乱码问题

【解决】字节输入流汉语乱码问题

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();
		}
		// 字节输入流
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值