当前位置:网站首页>Reader case of IO

Reader case of IO

2022-06-22 11:40:00 ITzhongzi

Core code

package ioDemo;

import java.io.*;
import java.nio.charset.Charset;

/** * outputStreamWriter  You can convert the output byte stream to character stream output  * InputStreamReader  Can convert the input byte stream to character stream  */
public class ChangeStreamDemo {
    
    public static void main(String[] args) {
    
        try {
    
// InputStream is = new FileInputStream("C:\\Users\\lihw\\Desktop\\test\\123.txt");
// read(is);
            OutputStream os = new FileOutputStream("C:\\Users\\lihw\\Desktop\\test\\123.txt");
            writeDemo(os);
        } catch (Exception e) {
    
            e.printStackTrace();
        }
    }

    public static void read(InputStream in) {
    
        try {
    
            Reader reader = new InputStreamReader(in, Charset.defaultCharset());
            char[] chars = new char[1024];
            int len = -1;
            while ((len = reader.read(chars)) != -1) {
    
                System.out.println(new String(chars, 0, len));
            }
            System.out.println(" Finished reading ");
            reader.close();
        }catch (Exception e) {
    
            e.printStackTrace();
        }
    }

    public static void writeDemo(OutputStream out) {
    
        try {
    
            Writer writer = new OutputStreamWriter(out);
            writer.write(" Have fun ");
            writer.close();
        } catch (Exception e) {
    
            e.printStackTrace();
        }
    }

}

原网站

版权声明
本文为[ITzhongzi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221111417090.html