A brief overview of character input stream Reader

Character input stream Reader composition structure

This article will give a brief summary of the character input stream Reader in the JAVA I/O stream:

In general, each character input stream class has a corresponding purpose, as follows:

    • Character stream base class: Reader
    • Byte stream to character stream: InputStreamReader //Read characters in the byte input stream
    • Character file reading related: FileReader //Read characters in the file
    • Convert character array to character stream: CharArrayReader //Read characters in character array
    • Thread internal communication (pipeline): PipedReader //Read characters in the pipe
    • String to character stream: StringReader //Read characters in a string
    • Buffered stream: BufferedReader //Can decorate other character input streams to add buffering function
    • Filter stream: FilterReader //can decorate other character input streams and add filtering functions
    • Parse Input: PushbackReader (can roll back for reading), LineNumberReader (displays line number) //can decorate other character input streams and add rollback reading and display line number functions

Let’s take a look at the structure of Reader (picture below);

Each character input stream will be introduced in detail below;

InputStreamReader

InputStreamReader inherits the character stream abstract class Reader. Each construction method contains a byte stream InputStream input parameter. The function is obvious, that is, obtaining the character stream through the byte stream InputStream;

PS: Whether it is the processing of byte streams in the construction method (StreamDecoder.forInputStreamReader) or the reading of character streams (StreamDecoder.read), the bottom layer is implemented through the StreamDecoder class. Those who are interested can learn more~

For example, as follows, for the convenience of reading, no exception handling is performed:

package io;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

public class IOTest {

    public static void main(String[] args) throws IOException {
        //Get a character input stream through the "standard" byte input stream
        Reader reader = new InputStreamReader(System.in);
        //Read a character and print
        System.out.println((char)reader.read());
        //Close the stream
        reader.close();
    }
}
//output example
//Keyboard input 0
//Display 0

FileReader

FileReader inherits the character stream InputStreamReader and gets the character stream through a local character file. Check its construction method. It all first generates a FileInputStream byte stream object based on the passed parameters, and then calls the construction method of the parent class InputStreamReader. Get character stream;

Give a simple example:

package io;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class IOTest {

    public static void main(String[] args) throws IOException {
        //Read the local file and get the character stream
        Reader reader = new FileReader("C:\test.txt");
        //Read a character and print
        System.out.println((char)reader.read());
        //Close the stream
        reader.close();
    }
}

CharArrayReader

CharArrayReader allows us to obtain a character stream through a character array. The construction method is as follows

Looking at the source code, you can find that the reference to the external character array is directly used in CharArrayReader. That is to say, even after obtaining the character stream object, when the external array is changed, the characters read through the stream will also change. The following code example:

package io;

import java.io.CharArrayReader;
import java.io.IOException;
import java.io.Reader;

public class IOTest {

    public static void main(String[] args) throws IOException {
        //Character array
        char[] charArr = new char[]{'a', 'b', 'c'};
        //Get the character stream through the character array in memory
        Reader reader = new CharArrayReader(charArr);
        //Change the element value of the array charArr
        charArr[0] = 'e';
        //Read a character and print
        System.out.println((char)reader.read());//Print the changed character 'e'
        //Close the stream
        reader.close();
    }
}

PipedReader

Character stream pipes can be created through PipedWriter and PipedReader, and threads can communicate through pipes. Note: There must be two threads in the same JVM;

PipedReader is generally used in conjunction with PipedWriter. One thread writes data to the pipe through PipedWriter, and the other thread reads data through the pipe. Note that reading and writing will block the thread, as shown in the following example:

package io;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class IOTest {

    public static void main(String[] args) throws IOException {
        final PipedWriter pw = new PipedWriter();
        final PipedReader pr = new PipedReader(pw);

        ExecutorService es = Executors.newFixedThreadPool(2);

        es.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    pw.write("hello~");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        es.execute(new Runnable() {

            @Override
            public void run() {

                char[] cbuffer = new char[6];
                try {
                    // Will cause the thread to block
                    pr.read(cbuffer, 0, 6);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(cbuffer);

            }
        });

    }
}

BufferedReader

This character stream can be used to decorate other character input streams and provide character buffers for other character input streams to avoid reading data from external media every time. The decorator mode in the design mode is used here. You can refer to what I wrote before of,

http://www.cnblogs.com/chenpi/p/5173818.html

The decorated character stream can have more behaviors, such as the readLine method, etc.;

As an example of use, read external files:

package io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class IOTest {

    public static void main(String[] args) throws IOException {
        //Read the local file and get the character stream. Here, set the buffer size to 10k
        BufferedReader reader = new BufferedReader(new FileReader("C:\test.txt"), 10 * 1024);
        //Read a line
        System.out.println(reader.readLine());
        System.out.println(reader.readLine());
        System.out.println(reader.readLine());
        //Close the stream
        reader.close();
    }
}

LineNumberReader

Inherits BufferedReader. In addition to the functions provided by BufferedReader, it also has the ability to obtain line number information.

Note that the setLineNumber method of LineNumberReader cannot implement skip reading of the stream

for example

package io;

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class IOTest {

    public static void main(String[] args) throws IOException {
        //Read the local file and get the character stream. Here, set the buffer size to 10k
        LineNumberReader reader = new LineNumberReader(new FileReader("C:\test.txt"), 10 * 1024);
        
        System.out.println(reader.getLineNumber());//Print the current line number
        System.out.println(reader.readLine());//Read a line
        System.out.println(reader.getLineNumber());
        System.out.println(reader.readLine());//Read a line
        //Close the stream
        reader.close();
    }
}

FilterReader

The abstract class FilterReader is the base class for implementing custom filtering of input character streams. From the perspective of source code implementation, it simply covers all the methods in Reader, which feels useless because there is already an abstract class Reader;

PushbackReader

Simply put, the PushbackReader character stream allows you to insert characters into the buffer by calling the unread method during the process of reading characters. The next time you read, read data from the buffer first. If there is no data in the buffer, then read from the stream. Pick;

This class also uses the decorator pattern;

Generally, PushbackReader can be used to complete the read rollback function. For example, the previously read characters can be inserted into the buffer by calling the unread method. The next time it is read, the previous data can be read again;

An example is as follows:

package io;

import java.io.FileReader;
import java.io.IOException;
import java.io.PushbackReader;

public class IOTest {

    public static void main(String[] args) throws IOException {
        // Read the local file and get the character stream. Here, set the buffer size to 1024k
        PushbackReader reader = new PushbackReader(new FileReader("C:\test.txt"), 1024);
        // read a character
        char a = (char) reader.read();
        System.out.println(a);
        // Push the read characters back into the stream
        //In fact, to put it simply, it means to store character a in the buffer. The next time you read it, read the data from the buffer first. If there is no data in the buffer, then read it from the stream.
        reader.unread(a);
        // Reread the previous word (in the buffer)
        System.out.println((char) reader.read());
        //Read data from the stream
        System.out.println((char) reader.read());
        // close the stream
        reader.close();
    }
}

StringReader

Converting a string into a character input stream is relatively simple. Here is an example of use:

package io;

import java.io.IOException;
import java.io.StringReader;

public class IOTest {

    public static void main(String[] args) throws IOException {
        // Get the character stream through the string
        StringReader reader = new StringReader("hello~");
        //Read data from the stream
        char[] cbuf = new char[6];
        reader.read(cbuf, 0, 6);
        System.out.println(cbuf);
        // close the stream
        reader.close();
    }
}