Java高级编程——I/O流解决乱码问题

27.13解决乱码问题

27.13.1字符输入流读取乱码

如下代码Test09_01,原本a.txt文件时UTF-8,运行Test09_01不会出先乱码,现在将a.txt文件改成GBK格式,再运行Test09_01代码读取文件内容时会出现乱码。

public class Test09_01 {
    public static void main(String[] args) {

        // 创建字符输入流对象
        Reader fr = null;
        try {
            fr  = new FileReader("code_java02\\a.txt");

            // 记录读取的汉字解码后的十进制数
            int ch;
            
            // 循环读取
            while ((ch = fr.read()) != -1){
                // System.out.println(ch);十进制数
                System.out.print((char) ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 释放资源
            try {
                fr.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
        }

    }
}
解决乱码:
    方案一:
    创建字符输入流对象时候,不创建FileReader对象用Reader接收,而是创建字符转换输入流:InputStreamReader(字节流InputStream,编码)的对象用Reader接收,这样可以在里面指定编码方式,即将编码方式设置成和文本文件编码方式一致即可。FileReader对象的方法中不能指定编码方式。

该进后代码如Test09_02下:

  方案二:
  直接将文本文件编码方式改成和idea编码方式一致。
public class Test09_02 {
    public static void main(String[] args) {

        // public int read()  读取数据,读到末尾返回-1

        // 创建字符输入流对象
        Reader fr = null;
        // 创建字节输入流对象
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("code_java02\\a.txt");
            fr  = new InputStreamReader(fis,"GBK");

            // 记录读取的汉字解码后的十进制数
            int ch;

            // 循环读取
            while ((ch = fr.read()) != -1){
                // System.out.println(ch);十进制数
                System.out.print((char) ch);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 释放资源
            try {
                fr.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
        }


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蔚一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值