Java Basics - other input and output streams in IO streams

1. Data input / output stream

Data input stream: DataInputStream
Data output stream: DataOutputStream
Features: you can write basic data types and read basic data types

Sample code

public class MyTest {
    public static void main(String[] args) throws IOException {
        // Data input and output streams:
        // Data input stream:
        // DataInputStream
        // Data output stream:
        // DataOutputStream
        // characteristic:
        // Basic data types can be written and read
        DataInputStream in = new DataInputStream(new FileInputStream("a.txt"));
        int i = in.readInt();
        double v = in.readDouble();
        boolean b = in.readBoolean();
        char c = in.readChar();
        System.out.println(i);
        System.out.println(v);
        System.out.println(b);
        System.out.println(c);
        in.close();
    }

    private static void writeData() throws IOException {
        DataOutputStream out = new DataOutputStream(new FileOutputStream("a.txt"));
        out.writeInt(100);
        out.writeDouble(3.14);
        out.writeBoolean(true);
        out.writeChar('a');
        out.close();
    }
}

2. Memory operation flow

a:Operation byte array
		ByteArrayOutputStream
		ByteArrayInputStream
		This stream is invalid, so it does not need to be closed
b:Operation character array
		CharArrayWrite
		CharArrayReader
c:Operation string
		StringWriter
		StringReader		

 Construction method: public ByteArrayOutputStream()
public class MyTest {
    public static void main(String[] args) throws IOException {
        //Memory operation flow: memory operation flow, which is not associated with files and only reads and writes in memory
       /* 
        Operation byte array
        ByteArrayOutputStream
        ByteArrayInputStream
        This stream is invalid, so it does not need to be closed*/

       /*
       * ByteArrayOutputStream
       * This class implements an output stream in which the data is written to a byte array. The buffer automatically grows as data is written.
       * You can use toByteArray() and toString() to get data.
            Invalid to close ByteArrayOutputStream.
             The methods in this class can still be called after the flow is closed without generating any IOException.
       * */


        // ByteArrayOutputStream()
        // Create a new byte array output stream.

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bos.write("study hard".getBytes());
        bos.write("make progress every day".getBytes());
        bos.write("Love life, love Java".getBytes());
        //Fetch all byte data
        byte[] bytes = bos.toByteArray();
        String s = new String(bytes);
        System.out.println(s);


        //If you put the byte data of String, you can get it this way
        String s1 = bos.toString();
        System.out.println(s1);

    }
}

3. Print stream

Byte stream print stream
Character print stream

Characteristics of print stream
a: Print streams can only operate on destinations,The data source cannot be manipulated(Unable to read data)
b: A data call that can manipulate any data type print() Method can write any data type
c: If we enable automatic refresh,Then call println,printf or format When one of the methods,The automatic refresh is complete

By creating the object below, you can start auto refresh and call it. println,printf or format When one of the methods,The automatic refresh is complete
  	  public PrintWriter(OutputStream out,  boolean autoFlush)	 Start automatic refresh
  	 public PrintWriter(Writer out,  boolean autoFlush)		Start automatic refresh

d: This stream can operate on files directly(You can directly manipulate the stream of files: That is, the parameters of the construction method can pass files or file paths)

PrintWriter enables automatic refresh and line feed

PrintWriter pw = new PrintWriter(new FileWriter("printWriter2.txt") , true) ;
	pw.println(true) ;
	pw.println(100) ;
	pw.println("China") ;

Print stream copy text file

This print stream can only write data,Unable to read data,
Then we should find a stream object that can read the data in the text file for reading operation.
And we like efficient streaming objects very much,So we can use BufferedReader Read data.

An overview of standard input and output streams and the nature of output statements

stay System There are two static member variables in this class:
public static final InputStream in: Standard input stream, The corresponding device is the keyboard
public static final PrintStream out: Standard output stream , The corresponding device is the display
  	System.in The type of is InputStream.
  	System.out The type of is PrintStream yes OutputStream Grandchildren FilterOutputStream Subclass of.

Byte print stream

public class MyTest {
    public static void main(String[] args) throws IOException {
        //Print stream: single, not paired, can only write data, not read data
        //Byte print stream
        // A print stream created by yourself is associated with a file
        PrintStream printStream = new PrintStream("hehe.text");
        printStream.write("aaaa".getBytes());
        printStream.write("\r\n".getBytes());
        printStream.println("asfasdfasdfasdfffff");
        printStream.print(true);
        printStream.println(3.14);

        printStream.close();

        //The byte print stream returned by System.out, and the associated device is the screen
        PrintStream out = System.out;
        out.println(200);
    }
}

PrintWriter uses

public class MyTest2 {
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter printWriter = new PrintWriter(new FileOutputStream("haha.txt"),true);
        //If automatic refresh is enabled, it is possible to complete this operation only when one of the methods println, printf, or format is called, rather than whenever a line break is just output.
        //printWriter.write("asfasdfasdfasdf");
        printWriter.flush();
        printWriter.println("asdfasdfasdf");
       printWriter.println("asdfasdfasdfasdf");
        //printWriter.flush();
        printWriter.close();
    }
}

Case demonstration: print stream copy text file

public class MyTest3 {
    public static void main(String[] args) throws IOException {
       
        BufferedReader reader = new BufferedReader(new FileReader("haha.txt"));
        PrintWriter printWriter = new PrintWriter(new FileOutputStream("ccc.txt"), true);

        while (true){
            String s = reader.readLine();
            if (s == null) {
                break;
            }
            printWriter.println(s);
        }
        reader.close();
        printWriter.close();
    }
}

Two ways to achieve keyboard entry

public class MyTest {
    public static void main(String[] args) throws IOException {
    //First, Scanner realizes keyboard entry
       // Scanner scanner = new Scanner(System.in);
     //The second is the readLine method of BufferedReader.
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true){
            System.out.println("Please enter data");
            String s = reader.readLine();
            if("886".equals(s)){
                break;
            }
            System.out.println(s);
        }
    }
}

Improvement of character buffer stream for output statement

  obtain System Lower in Member variable
	InputStream in = System.in ;
	 in Is a byte input stream object,Then we can read the data entered by the keyboard through this byte input stream object.
	 So since we want to read the data,Previously, we explained two ways to read data:
	  1. Read one byte at a time
	  2. Read one byte array at a time
 So what kind of reading method do we use in this place. After analysis,Neither of these two reading methods is appropriate.
Because the data is entered by the customer through the keyboard,And we want to read a row of data directly.
And since you want to read a row of data,Then we need to use readLine method,And this method belongs to BufferedReader Method of,
And we need to create one BufferedReader Object to read data.And here we are in It belongs to byte stream,And create BufferedReader Object needs a character stream,
We need to convert this byte stream into a character stream,So since you want to convert it,
Then you need to use the transformation flow. Need to use InputStreamReader.

4. Random access flow

RandomAccessFile Overview the biggest feature can read and write
RandomAccessFile Class does not belong to stream, yes Object Class. But it blends InputStream and OutputStream The function of.
Supports reading and writing of random access files.

RandomAccessFile The parent class of is Object , This stream object can be used to read data or write data.You can manipulate data of any data type.
We can pass getFilePointer Method to get the file pointer,And can pass seek Method to set the file pointer
public class MyTest4 {
    public static void main(String[] args) throws IOException {
        //writeData();
        //Read as you write
        RandomAccessFile out = new RandomAccessFile("e.txt", "rw");
        int i = out.readInt();
        //Get file pointer position
        long filePointer = out.getFilePointer();
        System.out.println("File pointer position:"+filePointer);
        boolean b = out.readBoolean();
        filePointer = out.getFilePointer();
        System.out.println("File pointer position:" + filePointer); 
        double v = out.readDouble();
        filePointer = out.getFilePointer();
        System.out.println("File pointer position:" + filePointer); 
        String s = out.readUTF();
        filePointer = out.getFilePointer();
        System.out.println("File pointer position:" + filePointer);
        System.out.println(i);
        System.out.println(b);
        System.out.println(v);
        System.out.println(s);
        //Sets the position of the file pointer
        out.seek(13);
        s = out.readUTF();
        filePointer = out.getFilePointer();
        System.out.println("File pointer position:" + filePointer);
        System.out.println(s);
    }

    private static void writeData() throws IOException {
        RandomAccessFile out= new RandomAccessFile("e.txt", "rw");
        out.writeInt(100);
        out.writeBoolean(true);
        out.writeDouble(3.2);
        out.writeUTF("ha-ha");
        out.close();
    }
}

5. Serialized stream and deserialized stream

The so-called serialization is to store objects in files through streaming.Note: this object needs to be overridden Serializable Interface can be serialized
	Deserialization: it is to restore the object stored in the file into an object in the form of stream
	Serialized stream:	ObjectOutputStream
	Deserialization stream:	ObjectInputStream

If there is no method in such an interface, we call it a marked interface (used to mark classes, equivalent to stamping a chapter on pork)
The premise that an object can be serialized is that the corresponding class of the object must implement the Serializable interface
serialization and deserialization

Serialization: the process of converting an object into a sequence of bytes is called object serialization

Deserialization: the process of restoring a byte sequence to an object is called object deserialization

When do I need serialization and deserialization?

When we only run Java instances in the local JVM, there is no need for serialization and deserialization, but when we need to persist objects in memory to disk and database,

When we need to interact with the browser for network transmission, we need to serialize and deserialize

As long as we persist or network transfer objects in memory, we need serialization and deserialization at this time

Case demonstration of serialization and deserialization 1

public class MyTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //   Serialization: save byte data of java object to hard disk
        //   Deserialization: byte data of java object is read back to memory
        // void writeObject (Object obj)
        // Writes the specified object to ObjectOutputStream.

        //writeData();
        readData();
    }

    private static void readData() throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.txt"));
        //Deserialization
        Student object = (Student) in.readObject();
        System.out.println(object);
    }

    private static void writeData() throws IOException {
        Student student = new Student("Zhang San",23);
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.txt"));
        //serialize
        out.writeObject(student);
        out.close();
    }
}

Serialization and deserialization case demonstration 2

public class MyTest2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //writeData();
       readData();
    }

    private static void readData() throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.txt"));
        //Deserialization
        Student object = (Student) in.readObject();
        System.out.println(object);
        object = (Student) in.readObject();
        System.out.println(object);
    }

    private static void writeData() throws IOException {
        Student student = new Student("Zhang San",23);
        Student student2 = new Student("Li Si", 24);
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.txt"));
        //serialize
        out.writeObject(student);
        out.writeObject(student2);
        out.close();
    }
}

6. How to solve the problem of yellow warning line during serialization?

Why display the value of the specified serialVersionUID when implementing the Serializable interface?

If the specified serialVersionUID is not displayed, the JVM will automatically generate a serialVersionUID according to the attributes during serialization, and then serialize it together with the attributes for persistence or network transmission. During deserialization, the JVM will automatically generate a new serialVersionUID according to the attributes, Then compare the new serialVersionUID with the old serialVersionUID generated during serialization. If it is the same, the deserialization is successful, otherwise an error is reported

If the serialVersionUID is specified, the JVM will still generate a serialVersionUID during serialization and deserialization, but the value is the specified value, so that the serialVersionUID of the old and new versions will be the same during deserialization

In actual development, what problems will be caused by not displaying the specified serialVersionUID? If our class is not modified after writing, it will certainly not be a problem, but this is impossible in actual development. Our class will continue to iterate. Once the class is modified, the old object deserialization will report an error. Therefore, in actual development, we will display and specify a serialVersionUID. It doesn't matter what the value is, as long as it remains unchanged

7. How to prevent member variables of objects from being serialized

Use the transient keyword to declare member variables that do not need to be serialized

private transient int age ;// You can prevent serialization of member variables from using transient
Note: static variables will not be serialized, because serialization is for objects, and the static attribute takes precedence over objects. It will be loaded with the loading of classes, so it will not be serialized.

8. Overview of properties and its use as a Map collection

The Properties class represents a persistent set of Properties.
Properties can be saved in or loaded from a stream.
Each key and its corresponding value in the attribute list is a string.
The Properties parent class is Hashtable
It belongs to a double column collection. The keys and values in this collection are strings. Properties cannot specify generics

Use of special functions of Properties
public Object setProperty(String key,String value)
public String getProperty(String key)
public Set stringPropertyNames()

Case demonstration

public class MyTest3 {
    public static void main(String[] args) {
        //Properties extends Hashtable<Object,Object>

        Properties properties = new Properties();
         //properties.put("name", "zhangsan");
        //The default key value is saved as String
        properties.setProperty("name","zhangsan");
        String name = properties.getProperty("name");
        //The second parameter is the default value. If the key does not find the corresponding value, the default value is returned
        String property = properties.getProperty("name2", "lisi");
    }
}

load() and store() functions of Properties

Properties and IO streams are used together:
Public void load (Reader): read key value pair data and store the data in Properties
Public void store (writer, writer, string comments) writes the key value pair data in the Properties collection to the file, and comments comments

public class MyTest4 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.setProperty("username","Tiger Wang");
        properties.setProperty("password","654321");
        //Key = value
        //Save the key value data in the collection to a file
        properties.store(new FileWriter("user.properties"),"User information");
    }
}
public class MyTest5 {
    public static void main(String[] args) throws IOException {
        //Read the configuration file. The key value in the file is spliced with = sign
        Properties properties = new Properties();
        properties.load(new FileReader("user.properties"));
        System.out.println(properties);
    }
}

9.SequenceInputStream

SequenceInputStream 
	Represents a logical concatenation of other input streams.
	It starts with an ordered set of input streams,
	And read from the first input stream until it reaches the end of the file, and then read from the second input stream,
	And so on until the end of the file containing the last input stream is reached
	a:Construction method
	SequenceInputStream(InputStream s1, InputStream s2) 
	Initialize the newly created by remembering these two parameters SequenceInputStream(These two parameters will be read in order, first s1,Then read s2),
	To provide from here SequenceInputStream Bytes read.
	b:Construction method
	SequenceInputStream(Enumeration<? extends InputStream> e) 
	 Initialize the newly created by remembering the parameters SequenceInputStream,The parameter must be of build runtime type InputStream Object Enumeration Type parameter.

Case demonstration: merge two MP3 songs into one MP3 file

public class MyTest {
    public static void main(String[] args) throws IOException {
        FileInputStream in1 = new FileInputStream("Ye Liyi - The new Shanghai Bund.mp3");
        FileInputStream in2 = new FileInputStream("Fireworks are easy to cool Live_Lin Zhixuan.mp3");

        SequenceInputStream in = new SequenceInputStream(in1, in2);
        FileOutputStream out = new FileOutputStream("C:\\Users\\Desktop\\Song Dalian sing 3.mp3");
        int len = 0;
        byte[] bytes = new byte[1024 * 8];
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        in.close();
        out.close();
    }
}

Keywords: Java

Added by assgar on Tue, 07 Dec 2021 13:09:10 +0200