(Byte stream and character stream) Reader character input stream

Reader character input stream

The Readr class is a type that implements character input streams. It belongs to an abstract class. The definition of this class is as follows:

public abstract class Reader extends Object implements Readable, Closeable

The Reader class does not provide the input processing operation of the entire string like the Writer class, and can only use the character array to receive.

  • Read a character: public int read() throws IOException
  • Read characters into an array: public int read​(char[] cbuf) throws IOException
  • Read characters into a part of the array (off-len): public abstract int read​(char[] cbuf, int off, int len) throws IOException (the number of characters read, if the end of the stream has been reached, -1 is returned )

Example: Realize data reading

package 字节流与字符流;

import java.awt.font.TextMeasurer;
import java.io.*;

public class Reader类 {
    public static void main(String[] args) throws IOException {
        File file = new File("F:"+File.separator+"Test"+File.separator+"test.txt"); //实例化一个文件类
        if(file.getParentFile().exists()){  //没有父路径
            file.getParentFile().mkdirs();  //创建一个父路径
        }
        Reader reader = new FileReader(file);   //实例化Reader对象
        char[] temp = new char[1024];   //创建一个缓冲区存放内容
        int length = reader.read(temp); //存储数据到数组保存数据长度
        String str = new String(temp,0,length); //截取0到数组长度的内容转换为字符串
        System.out.println(str);
        reader.close(); //关闭资源
    }
}

When the character stream is read, the processing operation can only be implemented in the form of an array.

Guess you like

Origin blog.csdn.net/weixin_46245201/article/details/112792144