Summary of unfamiliar knowledge points in Java basic learning (17) -- IO character stream and other streams

Posted by elitegosu on Fri, 04 Mar 2022 00:33:31 +0100

1. Character stream

Causes of character stream

  • Read English characters and numbers with byte stream
    • No problem can be displayed normally
  • Read Chinese characters with byte stream
    • There may be a problem

Codec

  • How is a character stored in a computer?
    • Based on a coding table, the corresponding integer value (coding value) is stored in the computer
  • code
    • The process of converting character data into coded values based on a coding table (converting what people understand into what computers understand)
  • decode
    • The process of converting coded values into character data based on a coding table (converting what computers understand into what adults understand)

Causes of garbled code

Inconsistent encoding and decoding

Chinese coding table: 'you' 123

Japanese coding table: 'の' 123

Coding table

ASCII: American standard information interchange code.
It can be represented by 7 bits of a byte. one hundred and twenty-eight
ISO8859-1: Latin code table. European code table
Represented by 8 bits of a byte. 0000 0000 - 1111 1111

GB2312: Chinese coding table of China.
GBK: China's Chinese coding table has been upgraded to integrate more Chinese characters and symbols.
GB18030: alternative version of GBK
BIG-5 Code: a traditional Chinese character coding scheme commonly used in Taiwan and Hong Kong, commonly known as "big five code".

Unicode: international standard code, which integrates a variety of characters.

UTF-8: variable length to represent a character.
Different from UTF-8, it defines an "interval rule", which can be compatible with ASCII coding to the greatest extent:

It encodes Unicode as 00000000-0000007F characters, representing 0111 1111 = 7F in a single byte
It encodes Unicode characters as 00000080-000007FF and represents them in two bytes
It encodes Unicode as 00000 800-0000ffff characters, represented by 3 bytes

1 byte 0xxxxxxx
2 bytes 110xxxxx 10xxxxxx
3 bytes 1110xxxx 10xxxxxx 10xxxxxx

utf-16:

The encoding table used by the jvm uses 2 bytes to encode and decode

Char: 2 bytes

Coding table commonly used in development

utf-8 GBK ISO8859-1 ASCII

Default coding table

  • Default utf-8 in idea
  • Operating system Win GBK

The essence of character stream
The essence of character stream: byte stream + encoding table

1.1 character output stream

1.1.1 abstract base class Writer


1.1.2 specific subclasses

1.1.2.1 OutputStreamWriter conversion stream

OutputStreamWriter is a bridge between character flow and byte flow: the specified charset Encode the characters to be written to the stream into bytes. The character set it uses can be specified by name or explicitly given, otherwise the platform's default character set will be accepted.
Construction method

OutputStreamWriter(OutputStream out) creates an OutputStreamWriter that uses the default character encoding.

OutputStreamWriter(OutputStream out, String charsetName) creates an OutputStreamWriter that uses the specified character set.

Example:``

package com.cskaoyan.charstream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * @description:
 * @author: songtao@cskaoyan.onaliyun.com
 **/

public class Demo {
    public static void main(String[] args) throws IOException {
        // The first construction method
        FileOutputStream fileOutputStream = new FileOutputStream("a.txt");
        // Use default character set utf-8
        OutputStreamWriter out = new OutputStreamWriter(fileOutputStream);
        
        // Second
        OutputStreamWriter outputStreamWriter = 
                new OutputStreamWriter(new FileOutputStream("a.txt"), "GBk");
    }
}

Member method
5 write methods

package com.cskaoyan.charstream;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * @description: write method
 * @author: songtao@cskaoyan.onaliyun.com
 **/

public class Demo2 {
    public static void main(String[] args) throws IOException {
        // Define string
        String s = "I'll write 65 pages for you ppt";

        // Create transform output stream object
        OutputStreamWriter out =
                new OutputStreamWriter(new FileOutputStream("a.txt"));
        // Write data
        // Write a single character
        //writeSingle(s, out);

        // Write character array
        //writeMuti(s, out);

        out.write(s);

        out.flush();
        out.close();
    }

    private static void writeMuti(String s, OutputStreamWriter out) throws IOException {
        char[] chars = s.toCharArray();
        out.write(chars);
    }

    private static void writeSingle(String s, OutputStreamWriter out) throws IOException {
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            // Write character by character
            out.write(chars[i]);
        }
    }
}

Simplified stream writer 2.1

Convenient class for writing character files
Construction method

FileWriter(File file) constructs a FileWriter object based on a given File object.
FileWriter (File, Boolean append) constructs a FileWriter object according to a given File object.
FileWriter(String fileName) constructs a FileWriter object according to the given file name.
FileWriter(String fileName, boolean append) constructs the FileWriter object according to the given file name and the boolean value indicating whether to attach the written data.

example:

public class Demo1 {
    public static void main(String[] args) throws IOException {
        // First kind
        FileWriter fileWriter = new FileWriter(new File("a.txt"));
        
        // Second
        FileWriter fileWriter1 = new FileWriter("a.txt");
    }
}

Member method

5 write methods

example

public class Demo2 {
    public static void main(String[] args) throws IOException {
        // Create file character output stream object
        FileWriter fileWriter = new FileWriter("a.txt");
        // Write data
        String s = "What is a happy planet?";
        fileWriter.write(s);
        fileWriter.close();
    }
}

1.1.2.3 BuffferedWriter

Writes text to the character output stream, buffering individual characters, providing efficient writing of individual characters, arrays, and strings.

Construction method

BufferedWriter(Writer out) creates a buffered character output stream that uses the default size output buffer.
BufferedWriter(Writer out, int sz) creates a new buffered character output stream using an output buffer of a given size.

Default buffer size

  • 16KB

Unique method

  • voidnewLine() writes a line separator.

example:

public class Demo {
    public static void main(String[] args) throws IOException {
        // Create buffered output stream object
        BufferedWriter bw = new BufferedWriter(
                new FileWriter("a.txt"));
        // Write data
        bw.write("RNG take the crown");
        bw.newLine();
        bw.write("Lu Benwei");
        bw.close();
    }
}

1.2 character input stream

1.2.1 abstract base class Reader


Member method

intread() reads a single character.
intread(char[] cbuf) reads characters into an array.
abstract intread(char[] cbuf, int off, int len)

read():

The character read as an integer ranges from 0 to 65535 (0x00-0xffff). If the end of the stream has been reached, it returns - 1

1.2.2 specific subclasses

1.2.2.1 InputStreamReader conversion stream

Construction method

  • InputStreamReader(InputStream in) creates an InputStreamReader that uses the default character set.
  • InputStreamReader(InputStream in, String charsetName) creates an InputStreamReader using the specified character set.

example:

public class Demo {
    public static void main(String[] args) throws IOException {
        // The first construction method
        InputStreamReader in = new InputStreamReader(
                new FileInputStream("a.txt"));
        // The second construction method
        InputStreamReader inputStreamReader = new InputStreamReader(
                new FileInputStream("a.txt"), "GBk");
    }
}

Member method

  • 3 read methods

Example: reading data

public class Demo2 {
    public static void main(String[] args) throws IOException {
        // Create input stream object
        InputStreamReader in = new InputStreamReader(
                new FileInputStream("a.txt"));
        // read data

        // single
        //readSingle(in);

        // Multiple
        readMuti(in);

        // close
        in.close();
    }

    private static void readMuti(InputStreamReader in) throws IOException {
        char[] chars = new char[1024];
        // readCount indicates the number of characters read
        int readCount = in.read(chars);
        System.out.println(new String(chars,0,readCount));
    }

    private static void readSingle(InputStreamReader in) throws IOException {
        int readData = in.read();
        System.out.println(((char) readData));

        int readData2 = in.read();
        System.out.println(((char) readData2));
    }
}

Copy file

  • Text file copy
public class Demo3 {
    public static void main(String[] args) throws IOException {
        // Create input stream object
        InputStreamReader in = new InputStreamReader(
                new FileInputStream("D:\\aa.txt"));
        // Create output stream object
        OutputStreamWriter out = new OutputStreamWriter(
                new FileOutputStream("aa.txt"));
        // Read and write
        // Single character mode
        //copySingle(in, out);

        // Multiple character mode
        char[] chars = new char[1024];
        int readCount;
        while ((readCount = in.read(chars)) != -1) {
            out.write(chars,0,readCount);
        }

        // close
        in.close();
        out.close();
    }

    private static void copySingle(InputStreamReader in, OutputStreamWriter out) throws IOException {
        int readData;
        while ((readData = in.read()) != -1) {
            out.write(readData);
        }
    }
}

Image file copy

public class Demo4 {
    public static void main(String[] args) throws IOException {
        InputStreamReader in = new InputStreamReader(
                new FileInputStream("D:\\mm.jpg"));
        OutputStreamWriter out = new OutputStreamWriter(
                new FileOutputStream("mm.jpg"));
        char[] chars = new char[1024];
        int readCount;
        while ((readCount = in.read(chars)) != -1) {
            out.write(chars,0,readCount);
        }
        out.flush();
        in.close();
        out.close();

    }
}
// Although the copy seems successful, it can't be opened at all

Garbled code problem solving

public class Demo5 {
    public static void main(String[] args) throws IOException {
        InputStreamReader in = new InputStreamReader(
                new FileInputStream("a.txt"),"GBk");
        char[] chars = new char[1024];

        int readCount = in.read(chars);
        System.out.println(new String(chars,0,readCount));
    }
}

1.2.2.2 FileReader simplified stream

Convenient class for reading character files

Construction method

FileReader(File file) creates a new FileReader given the File from which to read data.
FileReader(String fileName) creates a new FileReader given the file name from which to read data.

Member method

3 read methods

example:

public class Demo3 {
    public static void main(String[] args) throws IOException {
        //  Create a character file input stream

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

        // Read data
        char[] chars = new char[1024];
        int readCount = reader.read(chars);
        System.out.println(new String(chars, 0, readCount));

        reader.close();
    }
}

1.2.2.3 conversion flow VS simplified flow

  • The use of conversion flow is troublesome, and the use of simplified flow is relatively simple
  • The conversion stream can display the specified character set (construction method). The simplified stream has no way to specify the character set, and can only use the platform default character set

1.2.2.4 BufferedReader

Read the text from the character input stream and buffer each character, so as to realize the efficient reading of characters, arrays and lines.

Construction method

BufferedReader(Reader in) creates a buffered character input stream using the default size input buffer.
BufferedReader(Reader in, int sz) creates a buffered character input stream using an input buffer of the specified size.

Unique member method

StringreadLine() reads a line of text.

be careful:

Read a text line. A line is considered terminated by one of the following characters: line feed ('\ n'), carriage return ('\ r'), or carriage return followed by a line feed.

return:
The string containing the content of the line, without any line terminator. If the end of the stream has been reached, null will be returned

Demo:

public class Demo2 {
    public static void main(String[] args) throws IOException {
        // Create buffered input stream object
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        // Read data
        //readSingleLine(br);

        // while loop
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        br.close();
    }

    private static void readSingleLine(BufferedReader br) throws IOException {
        String s = br.readLine();
        System.out.println(s);
        String s2 = br.readLine();
        System.out.println(s2);
        String s3 = br.readLine();
        System.out.println(s3);
    }
}

2 other flows

2.1 data flow

Introduction: how to write an integer 1000 to a text file using a character stream?

There is no way to write java basic data types through byte stream and character stream, so there is data stream

2.1.1 DataOutputStream data output stream

The data output stream allows applications to write basic Java data types into the output stream in an appropriate manner. The application can then use the data input stream to read the data into the

Construction method

DataOutputStream(OutputStream out) creates a new data output stream and writes the data to the specified basic output stream.

Member method

  • Each java basic data type has a write method corresponding to it

Demo

public class Demo {
    public static void main(String[] args) throws IOException {
        // Use data stream
        // Create data output stream object
        DataOutputStream out = new DataOutputStream(
                new FileOutputStream("a.txt"));
        // Write integer 1000
        out.writeInt(1000);
        out.writeDouble(3.14);
        out.close();


        // Create data input stream object
        DataInputStream in = new DataInputStream(
                new FileInputStream("a.txt"));

        // Read data
        int i = in.readInt();
        System.out.println(i);
        double v = in.readDouble();
        System.out.println(v);
    }
}

2.1.2 DataInputStream data input stream

Construction method

DataInputStream(InputStream in) creates a DataInputStream using the specified underlying InputStream.

Member method:

  • Each java basic data type has a read method corresponding to it

be careful:

  • In what order we write, we need to read in the same order
public class Demo2 {
    public static void main(String[] args) throws IOException {
        write();
        read();
    }

    private static void read() throws FileNotFoundException, IOException {
        DataInputStream dis = new DataInputStream(
                new FileInputStream("dos.txt"));
        byte b = dis.readByte();
        System.out.println(b);
        short s = dis.readShort();
        System.out.println(s);
        int i = dis.readInt();
        System.out.println(i);
        long l = dis.readLong();
        System.out.println(l);
        float f = dis.readFloat();
        System.out.println(f);
        double d = dis.readDouble();
        System.out.println(d);
        char ch = dis.readChar();
        System.out.println(ch);
        boolean bb = dis.readBoolean();
        System.out.println(bb);
        dis.close();
    }

    private static void write() throws IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream(
                "dos.txt"));
        dos.writeByte(1);
        dos.writeShort(20);
        dos.writeInt(300);
        dos.writeLong(4000);
        dos.writeFloat(12.34f);
        dos.writeDouble(12.56);
        dos.writeChar('a');
        dos.writeBoolean(true);
        dos.close();
    }
}

2.2 print stream

practice:

Write a tool class PrintUtils

Member variable OutputStream

printInt(int) a method for writing data of type int

printIntLn(int) a method for writing data of type int with line breaks

printDouble(double) is a method for writing data of type double

double write method with print type

close method

Tip: the core method is to convert the corresponding data type into String and write text

public class PrintUtils {
    public OutputStream out;

    public PrintUtils(OutputStream out) {
        this.out = out;
    }

    public void printInt(int intType) throws IOException {
        String s = String.valueOf(intType);
        out.write(s.getBytes());
    }

    public void printlnInt(int intType) throws IOException {
        String s = String.valueOf(intType);
        out.write(s.getBytes());
        out.write(System.lineSeparator().getBytes());
    }
}

2.2.1 PrintStream byte print stream and printWriter character print stream

Four characteristics of print stream

  • You can only operate the destination, not the data source.

    • No input stream corresponds to it
  • You can manipulate any type of data.

    • By converting different types into strings
  • If automatic refresh is started, it can be refreshed automatically.

    • PrintWriter(Writer out, boolean autoFlush) creates a new PrintWriter.
    • autoFlush - boolean variable; If true, the println, printf, or format methods flush the output buffer

  • Stream that can manipulate files

    • Directly use the construction method to pass the file name as a parameter

2.2.2 standard input stream and standard output stream

  • Standard output stream system Out the default output device is the display
    • Is a byte print stream
  • Standard input stream system In the default input device is the keyboard
    • Is a normal byte input stream

practice:

Use system In to implement a nextLine function in Scanner

Demand: keep receiving the data input by the keyboard, and terminate the program when "88" is input

Tip: use BufferedReader

public class Demo7 {
    public static void main(String[] args) throws IOException {
        // Use conversion flow
        BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));
        //System.out.println("before");
        //String s = br.readLine();
        //System.out.println("after");
        //System.out.println(s);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            // Give a convention when you enter "88" break
            if (line.equals("88")) {
                break;
            }
        }
        br.close();
    }
}

2.3 object flow

Why is there an object stream?

Student student = new Student("Zhang San",18);
// Store the student object through the serialization stream 
// Restore the student object by deserializing the stream

2.3.1 ObjectOutPutStream serialized stream

Can only support Java io. The object of the serializable interface is written to the stream

Construction method

ObjectOutputStream(OutputStream out) creates an ObjectOutputStream that writes to the specified OutputStream.

Member method

writeObject(Object obj) writes the specified object to ObjectOutputStream.

2.3.2 ObjectInputStream deserialization stream

Construction method

ObjectIntputStream(InputStream in)

Member method

readObject()

be careful:

  • java.io.NotSerializableException

  • Serializable is an empty interface that only serves as a marker

  • transient The modified attribute will not be serialized, only the default value
    
  • java. io. The invalidclassexception class has changed. The serialVersionUID has changed

    • How to solve by force
    • static final long serialVersionUID = -1141965245606624166l;

3. Summary

typeByte output streamByte input streamCharacter output streamCharacter input stream
Base classOutputStreamInputStreamWriterReader
Document relatedFileOutputStreamFileInputStreamFileWriterFileReader
Buffer correlationBufferedOutputStreamBufferedInputStreamBufferedWriterBufferedReader
Conversion flowOutputStreamWriterInputStreamReader
data streamDataOutputStreamDataInputStream
Print streamPrintStreamPrintWriter
Object flowObjectOutputStreamObjectInputStream

Topics: Java