io stream summary, serialization and deserialization, and Properties collection

Posted by guru2k9 on Sun, 06 Mar 2022 14:57:08 +0100

IO stream

1. Classification of IO streams

Classification by flow direction:
Input stream (read data)
Output stream (write data)
Classification by data type:
Byte stream
Byte input stream read data InputStream
Byte output stream write out data OutputStream
Character stream
Character input stream read data Reader
Character output stream write out data Writer

2. Difference between node flow and processing flow

InputStream & outputstreamreader & writer are node streams. Node streams preceded by nouns such as File and other verbs are processing streams. It is thought that processing streams are added on the basis of node streams.
The input stream of java mainly uses InputStream and Reader as the base class, while the output stream mainly uses outputStream and Writer as the base class. They are all abstract base classes and cannot create instances directly.
Byte stream is mainly based on InputStream and outPutStream, while character stream is mainly based on Reader and Writer.

3. Byte output stream

It is an abstract class and cannot be instantiated directly. You need to find a concrete implementation subclass to instantiate FileOutputStream:

Construction method:
FileOutputStream(File file) creates a File output stream to write to the File represented by the specified File object.
FileOutputStream(String name) creates a file output stream and writes it to the file with the specified name.

Operation steps of byte output stream:
1. Create byte output stream object
2. Call method and write data
3. Release resources

Several methods of writing data in byte output stream:
public void write(int b)
public void write(byte[] b)
public void write(byte[] b,int off,int len)

4. Byte input stream

Similarly, use FileInputStream for instantiation

Construction method of FileInputStream
FileInputStream(File file)
FileInputStream(String name)

There are two ways to read data from byte input stream:
            FileInputStream Member method of
                public int read()You can only read one byte at a time and return ASCII Code value cast
                public int read(byte[] b)Read one byte array at a time
            //The first traversal method
              int i=0;
              while ((i=fis.read())!=-1){
              System.out.print((char) i);
              }

            //The second traversal method
            byte[] bytes = new byte[1024];
            int length=0;
            while ((length=fis.read(bytes))!=-1){
                System.out.println(new String(bytes,0,length));
            }

5. Code example 1 (text copy)

import java.io.FileInputStream;
import java.io.FileOutputStream;

/*
        Copy the contents of a.txt in the current project directory to b.txt in the current project directory

        Input stream
            InputStream -- FileInputStream
            Read one byte at a time
            Read one byte array at a time
            a.txt

        Output stream
            OutputStream -- FileOutputStream
            Write values of type int one at a time
            Write one byte array at a time
            Write part of a byte array one at a time
            b.txt


 */
public class CopyFileDemo1 {
    public static void main(String[] args) throws Exception {
        //1. Create byte input stream object and byte output stream object
        FileInputStream fis = new FileInputStream("a.txt");
        FileOutputStream fos = new FileOutputStream("f.txt");

        //2. Read data
        //a: Read one byte at a time
//        int i = 0;
//        while ((i=fis.read())!=-1){
            System.out.println();
//            fos.write(i);
//        }

        //b: Read one byte array at a time
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = fis.read(bytes)) != -1) {
            fos.write(bytes, 0, length);
        }

        //Release resources
        fos.close();
        fis.close();
    }
}

6. Code example 2 (photo copy)

import java.io.FileInputStream;
import java.io.FileOutputStream;

/*
        Put von Timo under the current project jpg is copied to the day23 directory of the current project

        Data source: from where
        Von Timo jpg -- read data -- InputStream -- FileInputStream

        Destination: where to go
        com\\shujia\\wyh\\day23\\ftm.jpg -- Write out data -- OutputStream -- FileOutputStream
 */
public class CopyJpgDemo1 {
    public static void main(String[] args) throws Exception {
        //Create byte input stream object and byte output stream object
        FileInputStream fis = new FileInputStream("Feng Timo.jpg");
        FileOutputStream fos = new FileOutputStream("src\\com\\shujia\\wyh\\day23\\ftm.jpg");

        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = fis.read(bytes)) != -1) {
            fos.write(bytes, 0, length);
        }

        //Release resources
        fos.close();
        fis.close();
    }
}

7. Byte buffer stream

Buffer class (efficient class)
Byte buffered output stream
BufferedOutputStream
Byte buffered input stream
BufferedInputStream

8. Character stream

Character input stream
Reader
Character output stream
Writer

OutputStreamWriter: character output stream is a conversion stream obtained by adding byte stream and encoding table. When writing data later, it can be written according to the encoding specified by itself
public OutputStreamWriter(OutputStream out)
Create an OutputStreamWriter that uses the default character encoding. According to the default encoding, characters are used as a bridge to convert the data of byte stream into character stream
public OutputStreamWriter(OutputStream out,String charsetName)
InputStreamReader: character input stream
public InputStreamReader(InputStream in)
Read the data and convert the data of byte stream into character stream with characters as a bridge according to the default encoding
public InputStreamReader(InputStream in,String charsetName)
Read the data and convert the data of byte stream into character stream with characters as a bridge according to the specified encoding
According to the specified encoding, characters are used as a bridge to convert the data of byte stream into character stream
Convert byte stream to character stream
Character stream = byte stream + encoding table

OutputStreamWriter How to write data:
            public void write(int c)
            public void write(char[] cbuf)
            public void write(char[] cbuf,int off,int len)
            public void write(String str)
            public void write(String str,int off,int len)

The difference between flush() and close():
1. After calling flush(), the stream object is not closed and can continue to write data.
2. After calling close(), the stream object is closed, and subsequent data cannot be written through this object.

InputStreamReader:Character input stream
            Method of reading data:
                public int read()
                public int read(char[] cbuf)

Code example (copy file with character stream)

import java.io.*;

/*
Copy the contents of a.txt in the current project directory to b.txt in the current project directory

        Data source:
            a.txt -- Read data -- character input stream -- Reader -- InputStreamReader

        destination:
            b.txt -- Write out data -- character output stream -- Writer -- OutputStreamWriter
 */
public class CopyFileDemo2 {
    public static void main(String[] args) throws IOException {
        //Create character input stream object and character output stream object
        InputStreamReader isr = new InputStreamReader(new FileInputStream("d.txt"));
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("dd.txt"));
        //First kind
//        int i=0;
//        while ((i=isr.read())!=-1){
//            osw.write(i);
//        }

        //Second
        char[] chars = new char[1024];
        int length=0;
        while ((length=isr.read(chars))!=-1){
            osw.write(chars,0,length);
        }
        //Free up space
        osw.close();
        isr.close();

    }
}

Copy text file with character buffer stream

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

/*
            Copy the contents of a.txt in the current project directory to b.txt in the current project directory

            Data source:
                a.txt -- Read data -- character input stream -- Reader -- InputStreamReader -- FileReader -- BufferedReader

            destination:
                b2.txt -- Write data -- character output stream -- Writer -- OutputStreamWriter -- FileWriter -- BufferedWriter
 */
public class CopyFileDemo4 {
    public static void main(String[] args) throws Exception {
        //1. Create character buffered input stream object and character buffered output stream object
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("b2.txt"));

        //Read and write one character array at a time
        char[] chars = new char[1024];
        int length = 0;
        while ((length= br.read(chars))!=-1){
            bw.write(chars,0,length);
            bw.flush();
        }

        //Release resources
        bw.close();
        br.close();

    }
}

Special reading and writing methods of character buffer stream:

       Special character buffer read / write method:
       BufferedWriter:
            void newLine()
            Write a line separator. The line separator string is determined by system properties line.separator Definition, not necessarily a single line break('\ n')Character.

       BufferedReader:
            public String readLine()
            Read a line of text. A line is treated as a newline character('\ n')´╝îCarriage return('\ r')Any one of the or subsequent newline terminations.

Code example

Store the string data in the ArrayList collection into a text file

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

/*
Store the string data in the ArrayList collection into a text file
 */
public class IOTest1 {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();

        list.add("java");
        list.add("hello");
        list.add("world");
        list.add("java");

        BufferedWriter bw=null;
        try {
            bw = new BufferedWriter(new FileWriter("a.txt"));
            for(String s:list){
                bw.write(s);
                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Data sorting

import java.io.*;
import java.util.Arrays;

/*
It is known that there is such a string in the s.txt file: "hcexfgijkamdnoqrzstuvwybpl"
            Please write a program to read the data content, sort the data and write it to SS Txt.
 */
public class IOTest2 {
    public static void main(String[] args)throws IOException {
        //Create character buffered input stream object
        BufferedReader br = new BufferedReader(new FileReader("s.txt"));
        String s = br.readLine();
        br.close();

        //Convert string to character array
        char[] chars = s.toCharArray();

        //Call the sort method of the Arrays tool class
        Arrays.sort(chars);

        //Create character buffered output stream object
        BufferedWriter bw = new BufferedWriter(new FileWriter("s.txt"));
        bw.write(chars);
        bw.flush();
        bw.close();
    }
}

Flow of operation basic data

Note: the read data should be the same as the written data

import java.io.*;

//The order of reading is consistent with that of writing
public class DataInputStreamDemo1 {
    public static void main(String[] args) throws IOException {
//        write();
        read();
    }

    private static void read() throws FileNotFoundException, IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("b3.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);

        int i = dis.readInt();
        System.out.println(i);
        short s = dis.readShort();
        System.out.println(s);
        byte b = dis.readByte();
        System.out.println(b);

        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();
    }
}

serialization and deserialization

Serialization:
The objects are stored in a text file or database in the same way as a stream, or transmitted in the network
Object – stream data: ObjectOutputStream
Deserialization:
Restore the stream object data in the text file or the stream data in the network to an object
Stream data – object: ObjectInputStream

serialVersionUID can be generated in two ways

One is the default 1L, for example: private static final long serialVersionUID = 1L;

The second is to generate a 64 bit hash field according to the class name, interface name, member method and attribute
When implementing Java io. When the Class of the serializable interface does not explicitly define a serialVersionUID variable, the Java serialization mechanism will automatically generate a serialVersionUID according to the compiled Class for sequential version comparison. In this case, if the Class file (Class name, method description, etc.) does not change (add spaces, line breaks, comments, etc.), Even if compiled many times, the serialVersionUID will not change

Place the cursor on the class name: alt+enter
private static final long serialVersionUID = -1761396628325683011L will be automatically generated;

Transient keyword
The function of transient keyword is to control the serialization of variables. Adding this keyword before the variable declaration can prevent the variable from being serialized into the file. After being deserialized, the value of transient variable is set to the initial value, such as 0 for int type and null for object type.

Some simple summaries of Java serialization
1. Java serialization only saves the state of the object. As for the methods in the object, serialization doesn't care
2. When a parent class implements serialization, the child class will automatically implement serialization without displaying the interface for serialization
3. When the instance variable of an object references other objects, the referenced objects will be serialized automatically when serializing the object (deep cloning is realized)
4. When a field is declared as transient, the default serialization mechanism will ignore this field
For fields declared as transient, if serialization is required, two private methods can be added: writeObject and readObject

Properties collection

Properties can be saved in or loaded from the stream. Each key and its corresponding value in the property list are a string, inherited from Hashtable

Characteristics of the Properties class
a) The collection cannot write generics
b) A set of attributes that can be persisted. Key values can be stored in the collection, hard disk, U SB flash disk, etc
c) It can be used in combination with technologies related to IO flow
The Properties collection is a double column collection. By default, both key and value are strings

import java.util.Properties;

/*
        user: root
        password: 123456
 */
public class PropertiesDemo {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "123456");


        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        System.out.println(user + "--" + password);


    }
}

Topics: Java Back-end