转换流(InputStreamReader、OutputStreamWriter)

本文主要介绍了在Java中如何进行字节流与字符流之间的转换,重点讨论了InputStreamReader和OutputStreamWriter的用法,强调了解决文件读写时因编码格式不一致导致的乱码问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文字乱码:

原因:文件写入时的编码格式和读取时的编码格式不一致

1.从字节流 转换成字符流

InputStreamReader

  • InputStreamReader(InputStream in): 创建一个使用默认字符集的字符流。

  • InputStreamReader(InputStream in, String charsetName): 创建一个指定字符集的字符流。

2. 从字符流 到字节流

OutputStreamWriter

  • OutputStreamWriter(OutputStream in): 创建一个使用默认字符集的字符流。

  • OutputStreamWriter(OutputStream in, String charsetName): 创建一个指定字符集的字符流。

//1.演示 字节流 转换成 字符流
public class Demo1 {
    public static void main(String[] args) throws Exception {
        //已知 字节输入流
        InputStream is = new FileInputStream("//D:/SGUIGU/ownnote/Day5/Day19-io/src/com/atguigu/io/hello.txt");

        //转为 字符输入流
        Reader reader = new InputStreamReader(is);

        //已知字节输出流
        OutputStream os= new FileOutputStream("//D:/SGUIGU/ownnote/Day5/Day19-io/src/com/atguigu/io/hello.txt");

        //转为 字符输出流
        Writer writer = new OutputStreamWriter(os);
    }
}

读取GBK编码的文件内容
通过转换流指定编码 ,然后解析文件内容

public class Demo2 {
    public static void main(String[] args) throws Exception {
        InputStream is = new FileInputStream("//D:/SGUIGU/ownnote/Day5/Day19-io/src/com/atguigu/io/hello.txt");
        Reader reader = new InputStreamReader(is,"GBK");

        BufferedReader br = new BufferedReader(reader);
        String str = null;

        while ((str=br.readLine())!=null){
            System.out.println(str);
        }
        br.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值