自学内容网 自学内容网

Java-I/O框架09:InputStreamReader、OutputStreamWriter使用

视频链接:16.24 转换流的使用_哔哩哔哩_bilibiliicon-default.png?t=O83Ahttps://www.bilibili.com/video/BV1Tz4y1X7H7?spm_id_from=333.788.videopod.episodes&vd_source=b5775c3a4ea16a5306db9c7c1c1486b5&p=24

1.InputStreamReader使用

package com.yundait.Demo05;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class InputStreamReaderDemo01 {

    public static void main(String[] args) throws Exception {

        //1创建InputStreamReader
        FileInputStream fis = new FileInputStream("C:\\Users\\Public\\Documents\\ggg1.txt");
        InputStreamReader isr = new InputStreamReader(fis, "gbk");//可以选择读取文件时使用的字符编码标准

        //2读取文件
        int data;
        while ((data = isr.read())!=-1){
            System.out.print((char) data);
        }
        //3关闭
        isr.close();
    }
}

2.OutputStreamWriter使用

package com.yundait.Demo05;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;

public class OutputStreamWriterDemo01 {
    public static void main(String[] args) throws Exception {

        //创建转换流
        FileOutputStream fos = new FileOutputStream("C:\\Users\\Public\\Documents\\ggg1.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");

        //写入文件

        for(int i=0; i<10; i++){
            osw.write("好好学习,天天向上\r\n");
            osw.flush();
        }

        //3关闭
        osw.close();
        System.out.println("执行完毕");

    }
}


原文地址:https://blog.csdn.net/zhangjinajian759/article/details/143471823

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!