java Foundation (24): Conversion Stream, Buffer Stream

Keywords: Java encoding network socket

1. Conversion flow

What does it mean to construct an InputStreamReader or OutputStreamWriter on the basis of byte streams when learning about character streams (FileReader, FileWriter)?

 

1.1 OutputStreamWriter class

 

Referring to the API introduction of Output Stream Writer, Output Stream Writer is a bridge between character flow and byte flow: you can use the specified character encoding table to encode the characters written into bytes. What it does is to convert strings into bytes according to the specified encoding table and write them out using byte streams.

 

Code demonstration:

public static void writeCN() throws Exception {
        //Create byte output stream objects associated with files
        FileOutputStream fos = new FileOutputStream("c:\\cn8.txt");
        //Create a conversion stream object that converts characters to bytes, and specify encoding
        OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
        //Call the transformation stream and write out the text, which is actually written to the buffer of the transformation stream.
        osw.write("Hello");//Write to the buffer.
        osw.close();
}

OutputStreamWriter stream object, how on earth does it convert characters into byte output?

In fact, we maintain our own buffer in the OutputStreamWriter stream. When we call the write method of the OutputStreamWriter object, we will take the characters to the specified code table to query, and store the encoding values of the characters into bytes in the OutputStreamWriter buffer. The refresh function is then invoked, or the stream is closed, or the byte data in the buffer is written to the specified file using the byte stream when the buffer is full.

1.2 InputStreamReader class

Referring to the API introduction of InputStreamReader, InputStreamReader is a bridge between byte flow and character flow: it reads bytes using the specified character encoding table and decodes them into characters. The character set it uses can be specified by name or explicitly given, or it can accept the platform default character set.

 

 

Code demo

 

public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
        //Demonstration of a byte-to-character stream conversion stream
        readCN();
    }
    public static void readCN() throws IOException{
        //Create byte stream objects to read files
        InputStream in = new FileInputStream("c:\\cn8.txt");
        //Creating Conversion Stream Objects 
        //InputStreamReader isr = new InputStreamReader(in);In this way, the object will be read by the local default code table, and error decoding will occur.
        InputStreamReader isr = new InputStreamReader(in,"utf-8");
        //Using Conversion Stream to Read Bytes in Byte Stream
        int ch = 0;
        while((ch = isr.read())!=-1){
            System.out.println((char)ch);
        }
        //Closed flow
        isr.close();
    }
}

Note: When reading a specified encoding file, it is necessary to specify the encoding format, otherwise decoding errors will occur and scrambling will occur.

1.3 Conversion flow and subclass distinction

The following inheritance relationships were found:

OutputStreamWriter:

  |--FileWriter:

InputStreamReader:

  |--FileReader;

 

What's the difference between the functions of parent and child classes?

Output Stream Writer and Input Stream Reader are bridges between characters and bytes: they can also be called character conversion streams. Character Conversion Stream Principle: Byte Stream + Coding Table.

FileWriter and FileReader: As subclasses, they exist only as convenient classes for manipulating character files. When the character file of operation is using the default encoding table, the operation can be completed directly with the subclass instead of the parent class, which simplifies the code.

InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"); and // default character set.

InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"),"GBK"); / / specifies the GBK character set.

FileReader fr = new FileReader("a.txt");

The functions of these three codes are the same, and the third one is the most convenient.

Note: Once you specify other encodings, you must never use subclasses, you must use character conversion streams. When do I use subclasses?

Conditions:

1. Documents are operated on. 2. Use default encoding.

Conclusion:

Byte - > Character: Understand - > Understand. Need to read. Input stream. Input Stream Reader

Characters - > bytes: understandable - > understandable. Need to write. Output stream. Output Stream Writer

2. Buffer flow

When we learn byte stream and character stream, we all read the data in the file. When we read the file with large amount of data, the speed of reading will be very slow, which will affect the efficiency of our program. So, I want to improve the speed, what can I do?

Java improves a set of buffer streams, which can improve the speed of reading and writing IO streams.

Buffer streams, byte buffer streams and character buffer streams are classified according to the classification of streams.

2.1 Byte Buffer Stream

There are two byte buffer streams according to the direction of the stream.

Write data to the stream, byte buffer output stream Buffered Output Stream

Read the data in the stream, byte buffer input stream BufferedInputStream

 

Both of them contain a buffer, which can improve the speed of reading and writing of IO streams.

2.1.1 Byte Buffered Output Stream

Read and write files and write data to files by byte buffer stream.

Construction method

Public Buffered Output Stream (Output Stream out) creates a new buffer output stream to write data to the specified underlying output stream.  

public class BufferedOutputStreamDemo01 {
    public static void main(String[] args) throws IOException {
        
        //Method of Writing Data to Files
        write();
    }

    /*
     * Method of Writing Data to Files
     * 1,Create stream
     * 2,Writing data
     * 3,Closed flow
     */
    private static void write() throws IOException {
        //Create a basic byte output stream
        FileOutputStream fileOut = new FileOutputStream("abc.txt");
        //Using efficient streams to encapsulate the basic streams to improve the speed
        BufferedOutputStream out = new BufferedOutputStream(fileOut);
        //2,Writing data
        out.write("hello".getBytes());
        //3,Closed flow
        out.close();
    }
}

2.1.2 Byte Buffered Input Stream

We just learned that the output stream implements the operation of writing data to a file, so now we complete the operation of reading data from a file.

Construction method

public BufferedInputStream(InputStream in) 

/*
 * Read data from a file
 * 1,Creating Buffer Stream Objects
 * 2,Read data, print
 * 3,Close
 */
private static void read() throws IOException {
        //1,Creating Buffer Stream Objects
        FileInputStream fileIn = new FileInputStream("abc.txt");
        //Packaging basic streams into efficient streams
        BufferedInputStream in = new BufferedInputStream(fileIn);
        //2,Read data
        int ch = -1;
        while ( (ch = in.read()) != -1 ) {
            //Printing
            System.out.print((char)ch);
        }
        //3,Close
        in.close();
}

2.1.3 Complete copying files using basic and efficient streams

We have been saying that efficient flow is fast and efficient, how to reflect it? You need to experience the pleasure of efficient streaming through a time-consuming comparison process of copying files.

/*
 * Requirement: Copy d:\test.avi file
 *         Reproduction in four ways
 *         Way 1: Using basic streams, copy one byte at a time takes 224613 milliseconds.
 *         Mode 2: Using a basic stream, assigning values in a multi-byte manner takes 327 milliseconds
 *         Way 3: Using efficient streaming, one byte at a time to replicate a total of 2047 milliseconds
 *         Mode 4: Using efficient streaming, assignment of multiple bytes takes 96 milliseconds
 * 
 * Data source: d:\test.avi
 * Destination 1: d:\copy1.avi
 * Destination 2: d:\copy2.avi
 * Destination 3: d:\copy3.avi
 * Destination 4: d:\copy4.avi
 * 
 * The steps of implementation are as follows:
 *     1,specify data source
 *     2,Designated destination
 *     3,Read data
 *     4,Writing data
 *     5,Closed flow
 * 
 */
public class CopyAVI {
    public static void main(String[] args) throws IOException {
        //Start timing
        long start = System.currentTimeMillis();
        //Mode 1: Copy one byte at a time using basic streams
        //method1("d:\\test.avi", "d:\\copy1.avi");
        //Mode 2: Assignment in a basic stream, with multiple bytes
        //method2("d:\\test.avi", "d:\\copy2.avi");
        //Mode 3: Replicate one byte at a time using efficient streams
        //method3("d:\\test.avi", "d:\\copy3.avi");
        //Mode 4: adopt efficient stream and assign value in the way of multiple bytes
        method4("d:\\test.avi", "d:\\copy4.avi");
        
        //Closing time
        long end = System.currentTimeMillis();
        //How many milliseconds does printing take?
        System.out.println("Total time consuming " +(end - start)+ "Millisecond");
    }
    
    //Mode 4: Assignment using efficient streaming, one byte or more
    private static void method4(String src, String dest) throws IOException {
        //1,specify data source
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
         //2,Designated destination
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
         //3,Read data
        byte[] buffer = new byte[1024];
        int len = -1;
        while ( (len = in.read(buffer)) != -1) {
            //4,Writing data
            out.write(buffer, 0, len);
        }
         //5,Closed flow
        in.close();
        out.close();
    }

    //Mode 3: Replicate one byte at a time using efficient streams
    private static void method3(String src, String dest) throws IOException {
        //1,specify data source
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
         //2,Designated destination
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
         //3,Read data
        int ch = -1;
        while ((ch=in.read()) != -1) {
            //4,Writing data
            out.write(ch);    
        }        
         //5,Closed flow
        in.close();
        out.close();
    }

    //Mode 2: Assignment in a basic stream, with multiple bytes
    private static void method2(String src, String dest) throws IOException {
        //1,specify data source
        FileInputStream in = new FileInputStream(src);
        //2,Designated destination
        FileOutputStream out = new FileOutputStream(dest);
        //3,Read data
        byte[] buffer = new byte[1024];
        int len = -1;
        while ( (len=in.read(buffer)) != -1) {
            //4,Writing data
            out.write(buffer, 0, len);
        }
        //5,Closed flow
        in.close();
        out.close();
    }

    //Mode 1: Copy one byte at a time using basic streams
    private static void method1(String src, String dest) throws IOException {
        //1,specify data source
        FileInputStream in = new FileInputStream(src);
        //2,Designated destination
        FileOutputStream out = new FileOutputStream(dest);
        //3,Read data
        int ch = -1;
        while (( ch=in.read()) != -1) {
            //4,Writing data
            out.write(ch);
        }
        //5,Closed flow
        in.close();
        out.close();
    }
}

2.2 Character Buffer Stream

Character buffered input stream BufferedReader

Character buffer output stream Buffered Writer

Complete efficient operation of writing and reading text data

2.2.1 Buffered Writer, Character Buffered Output Stream

Write text to the character output stream and buffer each character to provide efficient writing of individual characters, arrays and strings.

Method:

void newLine() writes a newline character based on the current system

/*
 * BufferedWriter Character buffered output stream
 * Method
 *     public void newLine()Write a line separator
 * 
 * Requirements: Write data to files by buffering output streams
 * Analysis:
 *     1,Create stream objects
 *     2,Writing data
 *     3,Closed flow
 * 
 */
public class BufferedWriterDemo {
    public static void main(String[] args) throws IOException {
        //Create stream
        //Basic character output stream
        FileWriter fileOut = new FileWriter("file.txt");
        //Packaging basic streams
        BufferedWriter out = new BufferedWriter(fileOut);
        //2,Writing data
        for (int i=0; i<5; i++) {
            out.write("hello");
            out.newLine();
        }
        //3,Closed flow
        out.close();
    }
}

2.2.2 Character buffer input stream BufferedReader

Read the text from the character input stream and buffer each character to achieve efficient reading of characters, arrays and rows.

Method

public String readLine() reads a text line, a string containing the contents of that line, without any line terminators, and returns null if it reaches the end of the stream

/*
 * BufferedReader Character buffered input stream
 * 
 * Method:
 *     String readLine() 
 * Requirements: Read data from files and display data
 */
public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
        //1,Create stream
        BufferedReader in = new BufferedReader(new FileReader("file.txt"));
        //2,Read data
        //One character at a time
        //One character array at a time
        //Read the string content of a line of text at a time
        String line = null;
        while( (line = in.readLine()) != null ){
            System.out.println(line);
        }
        
        //3,Closed flow
        in.close();
    }
}

2.2.3 Use Character Buffer Stream to Complete Text File Replication

We just finished learning about buffer streams. Now we use the unique function of character buffer streams to copy text files.

/*
 * Using efficient character buffer stream to complete the assignment of text file
 * 
 * Data source: file.txt
 * Destination: copyFile.txt
 * 
 * Analysis:
 *     1,Specifies a data source, which reads data from a data source using an input stream.
 *     2,Destination is to write data to a destination using an output stream
 *     3,Read data
 *     4,Writing data
 *     5,Closed flow
 */
public class CopyTextFile {
    public static void main(String[] args) throws IOException {
        //1,Specifies a data source, which reads data from a data source using an input stream.
        BufferedReader in = new BufferedReader(new FileReader("file.txt"));
        //2,Destination is to write data to a destination using an output stream
        BufferedWriter out = new BufferedWriter(new FileWriter("copyFile.txt"));
        //3,Read data
        String line = null;
        while ( (line = in.readLine()) != null ) {
            //4,Writing data
            out.write(line);
            //Write line breaks
            out.newLine();
        }
        //5,Closed flow
        out.close();
        in.close();
    }
}

3. Rules of flow operation

There are many objects in the IO stream. Which object should be used to solve the problem (when processing data on the device)?   

The IO flow is summarized regularly (four definitions):

Clear one: the data to be operated on is the data source or the data purpose.

Source: InputStream Reader

Objective: Output Stream Writer

First, make sure you want to read or write according to your needs.

 

Clear 2: Is the data to be manipulated byte or text?

Source:

Bytes: InputStream

Text: Reader

Objective:

Byte: Output Stream

Text: Writer

It has been made clear to the specific system.

 

Clear 3: Clear the specific equipment where the data is located.

Source equipment:

Hard Disk: File begins.

Memory: Array, string.

Keyboard: System.in;

Network: Socket

Aim Equipment:

Hard Disk: File begins.

Memory: Array, string.

Screen: System.out

Network: Socket

It is perfectly possible to specify which stream object to use.

 

Clear 4: Do you need additional functionality?

Additional functions:

Conversion? Conversion flow. Input Stream Reader Output Stream Writer

Is it efficient? Buffer object. BufferedXXX

InputStream

       FileInputStream

       BufferedInputStream

OuputStream

  FileOutputStream

  BufferedOuputStream

Writer

  OutputStreamWriter

  FileWriter

  BufferedWriter

Reader

  InputStreamReader

  FileReader

  BufferedReader

Posted by Jude on Fri, 11 Oct 2019 02:44:51 -0700