This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

IO stream

🚦JavaIO stream, which is a computer term. It is mainly used to process the transmission stream of data. There are four abstract classes for IO streams: Reader, Writer, InputStream, and OutputStream.

Classification of I/O streams

  • According to the flow direction, can be divided intoThe input stream InputStreamandThe output stream OutputStream;
  • According to the processing data unit, can be divided intoByte stream (InputStream, OutputStream)andCharacter stream (Reader, Writer);
  • By stream roleThe node flow(It is not convenient to connect directly to the data source for reading and writing) andProcessing flow(On the basis of the node stream, another layer is added to become a processing stream, high efficiency, such as BufferedInputStrean).

🚩🚩 Note: the input stream can only read data and the output stream can only write data, so we need to use different streams depending on the characteristics of the data to be transmitted.

Divided by operation mode

  • The node flow:A FileInputStream, FileReaderEtc.
  • Process flow:BufferedWriter, BufferedInputStreamEtc.

🚩🚩 Note: reading and writing is from the perspective of memory. For example, character reading refers to the reading of data from a disk file into memory in the form of characters, and write refers to the writing of data from memory into a disk file.

By operation object

  1. File operations: FileInputStream, FileOutputStream, FileReader, FileWriter, etc

  2. Pipeline operation: PipedInputStream and so on

  3. Array operations:

    • Character array: CharArrayReader, CharArrayWriter

    • Byte array: ByteArrayInputStream, ByteArrayOutputStream

  4. Buffering operations: BufferedWriter, BufferedInputStream, etc

  5. Basic data type operations: DataOutputStream, DataInputStream

  6. Object serialization: ObjectOutputStream, ObjectInputStream

  7. Conversion operations: InputStreamReader, OutputStreamWriter

  8. Print control: PrintStream, PrintWriter

Byte InputStream InputStream

InputStream is the parent class of all classes that represent byte input streams. InputStream is an abstract class. Abstract classes cannot create objects directly, so we need to use subclasses. Common subclasses of InputStream are FileInputStream, which reads data from a local file, ByteArrayInputStream, which reads data from an array of bytes, and StringBufferInputStream, which buffers strings The input stream represents reading data from the string buffer.

InputStream defines some member methods common to subclasses

  • Public abstract int read() reads a piece of data from an input stream and returns the ASCII value of the data

  • Public int read(byte[] b) Specifies the number of bytes read from the input stream. By default, the byte[] array is used to buffer multiple bytes read at a time.

  • Int read(byte b[], int off, int len) Reads len bytes from the off position into a byte array

  • Int available() Returns the number of bytes that can be read

  • Long skip(long N) Skip the specified number of bytes without reading

  • Public void close() closes the input stream and frees all system resources associated with the stream

FileInputStream File byte input stream

FileInputStream extends InputStream. A FileInputStream extends InputStream. A FileInputStream reads data from a local file into memory.

The common constructor for a FileInputStream

  • public FileInputStream(String name)To create a FileInputStream by opening a connection to the actual file. The name parameter indicates the full path name of the local file to be read.
public FileInputStream(String name) throws FileNotFoundException { this(name ! = null ? new File(name) : null); }Copy the code
  • public FileInputStream(File file)Create a FileInputStream by opening a connection to the actual file, with the file argument representing the file object of the file to be read
public FileInputStream(File file) throws FileNotFoundException { String name = (file ! = null ? file.getPath() : null); SecurityManager security = System.getSecurityManager(); if (security ! = null) { security.checkRead(name); } if (name == null) { throw new NullPointerException(); } if (file.isInvalid()) { throw new FileNotFoundException("Invalid file path"); } fd = new FileDescriptor(); fd.attach(this); path = name; open(name); FileCleanable.register(fd); // open set the fd, register the cleanup }Copy the code

The use of a FileInputStream

FileInputStream fis = new FileInputStream("C:\\Java\\test.txt"); File File = new File(C:\\Java\\test.txt"); FileInputStream fis2 = new FileInputStream(file); //2.1 Call the read method on the FileInputStream object to read a byte from the input stream int s = fis.read(); System.out.println((char)s); Int data=0; // Return the next byte of data, or -1 if the end of the file is reached while((data=fis.read())! =-1){ System.out.println((char)data); Byte [] b = new byte[6]; Fis.read (b); String s1 = new String(b); System.out.println(s1); Fis.close (); //3.Copy the code

ByteArrayInputStream ByteArrayInputStream

ByteArrayInputStream ByteArrayInputStream reads data from the specified byte array into memory

Constructor of ByteArrayInputStream

  • public ByteArrayInputStream(byte buf[])Pass in a specified buffer size
public ByteArrayInputStream(byte buf[]) {
    this.buf = buf;
    this.pos = 0;
    this.count = buf.length;
}
Copy the code
  • public ByteArrayInputStream(byte buf[], int offset, int length)
/** * @param buf Buffer size * @param offset Index subscript of the first byte to read from the byte array * @param Length Maximum number of bytes to read from the byte array */ public ByteArrayInputStream(byte buf[], int offset, int length) { this.buf = buf; this.pos = offset; this.count = Math.min(offset + length, buf.length); this.mark = offset; }Copy the code

The use of ByteArrayInputStream

Public static void main(String[] args) {byte[] bytes = {97,98,99,100}; ByteArrayInputStream BAis = new ByteArrayInputStream(bytes,1,2); int data; while((data =bais.read())! =-1){ System.out.print(data); } Output: 9899}Copy the code

Byte OutputStream OutputStream

OutputStream is the parent class of all classes that represent byte output streams. OutputStream is an abstract class. Abstract classes cannot create objects directly, so we need to use subclasses. Common subclasses of InputStream are FileOutputStream, a file byte InputStream that writes data to a local file, and ByteArrayOutputStream, a byte array InputStream that writes data from memory to a specified array of bytes.

OutputStream defines some member methods common to subclasses

  • Void close() closes the output stream and frees all system resources associated with the stream

  • Void Flush () flushes the output stream, writing out data from the buffer

  • Abstract void write(int b) writes the specified byte to the output stream

  • Void write(byte[] b) Writes the bytes of B. length from the specified byte array

  • Void write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to the output stream

FileOutPutStream File byte output stream

FileOutputStream extends OutputStream. A FileOutputStream extends OutputStream. A FileOutputStream extends OutputStream.

The common constructor for a FileOutputStream

  • FileOutputStream(String name, boolean append)Create a FileOutputStream based on the full path name of an existing file. Append indicates whether to append
public FileOutputStream(String name, boolean append) throws FileNotFoundException { this(name ! = null ? new File(name) : null, append); }Copy the code
  • FileOutputStream(String name)Creates a FileOutputStream based on the full path name of an existing file. Append defaults to false and does not append
public FileOutputStream(String name) throws FileNotFoundException { this(name ! = null ? new File(name) : null, false); }Copy the code
  • FileOutputStream(File file)Creates a FileOutputStream from a specified File object. Append is false by default and no append is applied.
public FileOutputStream(File file) throws FileNotFoundException {
    this(file, false);
}
Copy the code
  • FileOutputStream(File file, boolean append)Creates a FileOutputStream from the specified File object. Append indicates whether to append
public FileOutputStream(File file, boolean append) throws FileNotFoundException { String name = (file ! = null ? file.getPath() : null); SecurityManager security = System.getSecurityManager(); if (security ! = null) { security.checkWrite(name); } if (name == null) { throw new NullPointerException(); } if (file.isInvalid()) { throw new FileNotFoundException("Invalid file path"); } this.fd = new FileDescriptor(); fd.attach(this); this.path = name; open(name, append); FileCleanable.register(fd); // open sets the fd, register the cleanup }Copy the code

The use of FileOutputStream

public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("C:\Study\aaa.tx",true); 99,98,97 byte [] b = {}; // Write the byte array b to the output stream fos.write(b); fos.close(); }Copy the code

ByteArrayOutputStream Byte array input stream

ByteArrayOutputStream writes data from memory to a byte array input stream. The byte array input stream writes data to a defined buffer. The default buffer size is 32 and will automatically expand. Output as a byte array.

Constructor of ByteArrayOutputStream

  • ByteArrayOutputStream()Creates a ByteArrayOutputStream using the default buffer size of 32
public ByteArrayOutputStream() {
    this(32);
}
Copy the code
  • ByteArrayOutputStream(int size)Creates a ByteArrayOutputStream with the specified buffer size.
public ByteArrayOutputStream(int size) {
    if (size < 0) {
        throw new IllegalArgumentException("Negative initial size: "
                                           + size);
    }
    buf = new byte[size];
}
Copy the code

The use of ByteArrayOutputStream

Public static void main(String[] args) throws IOException {// create a FileInputStream. FileInputStream in = new FileInputStream(new) File("C:\Study\aaa.txt")); // create a ByteArrayOutputStream ByteArrayOutputStream out = new ByteArrayOutputStream(); int data = 0; // Loop through the data in the file input stream while((data = in.read())! = -1){// Write the data to the buffer of the byte array out.write(data); } // Obtain the data in the memory buffer byte[] bytes = out.tobytearray (); for (int i = 0; i < bytes.length; i++) { System.out.println((char)bytes[i]); } in.close(); out.close(); }Copy the code

Character Reader

Reader is an abstract class for reading characters, and its immediate subclasses are FileReader, which reads the data in the file into memory as characters, BufferedReader, which buffers the character input stream, which reads the data from the character input stream and then buffers the characters, An important subclass of Reader is InputStreamReader, which converts byte streams to character streams.

Member methods that are common to some subclasses defined in Reader

  • int read(CharBuffer target)Reads bytes into the character cache
  • dduqint read()Reading a single character
  • int read(char cbuf[]) Reads characters into the specified char array
  • int read(char cbuf[], int off, int len)Reads len characters from off into the char array
  • long skip(long n)Skipping the number of characters of the specified length does not read

FileReader

FilReader is directly inherited from InputStreamReader and reads the stream character by character. We use FileReader to call methods such as read() directly from its parent InputStreamReader class. The FilReader class has only constructors, no idiom methods or attributes.

FileReader constructor

  • FileReader(String fileName) Creates a file character input stream based on the full pathname of the local file
public FileReader(String fileName) throws FileNotFoundException {
    super(new FileInputStream(fileName));
}
Copy the code
  • FileReader(File file)Creates a File character input stream from a File object.
public FileReader(File file) throws FileNotFoundException {
    super(new FileInputStream(file));
}
Copy the code
  • FileReader(String fileName, Charset charset)Creates a file character input stream based on the full pathname of the local file and specifies the character set
public FileReader(String fileName, Charset charset) throws IOException {
    super(new FileInputStream(fileName), charset);
}
Copy the code
  • FileReader(File file, Charset charset)Creates a File character input stream from a File object and specifies a character set.
public FileReader(File file, Charset charset) throws IOException {
    super(new FileInputStream(file), charset);
}
Copy the code

The use of FileReader

public static void main(String[] args) throws IOException {
    FileReader fileReader = new FileReader(new File("C:\Study\aaa.txt"));
    int data;
    while ((data =fileReader.read()) != -1) {
        System.out.println(data);
    }
}
Copy the code

Write the character Writer.

Writer is a stream of write characters in JavaIo. Writer, like Reader, is an abstract class. The main subclasses are FileWriter for writing streams of file characters, BufferedWriter for caching streams of characters, and OutputStreamWriter for converting between byte streams and character streams.

🚲Writer Some methods common to subclasses

  • void write(int c)Write a character
  • void write(char cbuf[])Write an array of characters
  • void write(char cbuf[], int off, int len)Writes the number of len characters from the off position of the character array
  • void write(String str) Write a string
  • void write(String str, int off, int len)Writes the number of len characters from the off position of the string
  • Writer append(CharSequence csq)To append a sequence of characters
  • Public void flush() Force flush to write data to the buffer

FileWriter

FileWriter inherits OutputStreamWriter directly. It contains only multiple constructors, no attributes or member methods, and calls methods of its parent OutputStreamWriter.

🛹 Several constructors of a FileWriter

  • FileWriter(String fileName)Creates a file character write stream based on the full path file name of an existing file
public FileWriter(String fileName) throws IOException {
    super(new FileOutputStream(fileName));
}
Copy the code
  • FileWriter(String fileName, boolean append)Append is added to the constructor to indicate whether to append. The default is no.
public FileWriter(String fileName, boolean append) throws IOException {
    super(new FileOutputStream(fileName, append));
}
Copy the code
  • FileWriter(File file)Create a FileWriter File character write stream based on a File object File.
public FileWriter(File file) throws IOException {
    super(new FileOutputStream(file));
}
Copy the code
  • FileWriter(File file, boolean append)
public FileWriter(File file, boolean append) throws IOException {
    super(new FileOutputStream(file, append));
}
Copy the code
  • FileWriter(String fileName, Charset charset)According to the specifiedcodingAnd the file name to create a file character write stream.
public FileWriter(String fileName, Charset charset) throws IOException { super(new FileOutputStream(fileName), charset); } FileWriter FileWriter = new FileWriter("C:\Study\ aa.txt", charset.forname (" utF-8 "));Copy the code
  • FileWriter(String fileName, Charset charset, boolean append)
public FileWriter(String fileName, Charset charset, boolean append) throws IOException {
    super(new FileOutputStream(fileName, append), charset);
}
Copy the code

The use of 🛴 FileWriter

public static void main(String[] args) throws IOException {
    FileWriter fw = new FileWriter(new File("C:\Study\aaa.txt"));
    fw.write("FileWriter");
    fw.close();
}
Copy the code

Transformation flows

InputStreamReader implements the conversion of a byte stream to a character stream. Is a bridge between byte flow and character flow. If the character set encoding is not specified, the decoding process uses the platform default character encoding utF-8. OutputStreamWriter converts a character stream to a byte stream. Is a bridge between character flow and byte stream. If the character set encoding is not specified, the decoding process uses the platform default character encoding utF-8.

InputStreamReader 

The InputStreamReader class is a bridge from a byte stream to a character stream. It reads bytes using the specified character encoding and decodes them into characters.

🏍 several constructors of InputStreamReader

  • InputStreamReader(InputStream in)Create an InputStreamReader stream that uses the default character set.
public InputStreamReader(InputStream in) { super(in); try { sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## check lock object } catch (UnsupportedEncodingException e) { // The default encoding should always be available throw new Error(e); }}Copy the code
  • InputStreamReader(InputStream in, Charset cs)Creates an InputStreamReader that uses the given character set
public InputStreamReader(InputStream in, Charset cs) {
    super(in);
    if (cs == null)
        throw new NullPointerException("charset");
    sd = StreamDecoder.forInputStreamReader(in, this, cs);
}
Copy the code
  • InputStreamReader(InputStream in, String charsetName)Create an InputStreamReader that uses a named character set
public InputStreamReader(InputStream in, String charsetName)
    throws UnsupportedEncodingException
{
    super(in);
    if (charsetName == null)
        throw new NullPointerException("charsetName");
    sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
}
Copy the code

🛹 commonly used API

  • String getEncoding()Returns the name of the character encoding used by this stream
  • int read()Read a character

The use of 🏍 InputStreamReader

Public static void main(String[] args) throws IOException {//a: Create an InputStreamWriter, Fis = new FileInputStream("C:\Study\a.txt"); InputStreamReader isw = new InputStreamReader(fis,"utf-8"); Int len=0; int len=0; int len=0; while((len=isw.read())! =-1){ System.out.print((char)len); } //c: release resources isw.close(); fis.close(); }Copy the code

OutputStreamWriter

🚲 Several constructors of OutputStreamWriter

  • OutputStreamWriter(OutputStream out)Create an OutputStreamWriter stream that uses the default character encoding
public OutputStreamWriter(OutputStream out) { super(out); try { se = StreamEncoder.forOutputStreamWriter(out, this, (String)null); } catch (UnsupportedEncodingException e) { throw new Error(e); }}Copy the code
  • OutputStreamWriter(OutputStream out, Charset cs)Creates an OutputStreamWriter stream that uses the given character set
public OutputStreamWriter(OutputStream out, Charset cs) {
    super(out);
    if (cs == null)
        throw new NullPointerException("charset");
    se = StreamEncoder.forOutputStreamWriter(out, this, cs);
}
Copy the code
  • OutputStreamWriter(OutputStream out, String charsetName)Create an OutputStreamWriter stream that uses a named character set
public OutputStreamWriter(OutputStream out, String charsetName)
    throws UnsupportedEncodingException
{
    super(out);
    if (charsetName == null)
        throw new NullPointerException("charsetName");
    se = StreamEncoder.forOutputStreamWriter(out, this, charsetName);
}
Copy the code

🛴 commonly used API

  • void flush()Refresh the flow.
  • String getEncoding() Returns the name of the character encoding used by this stream.
  • void write(char[] cbuf, int off, int len)Writes part of a character array.
  • void write(int c)Write a character
  • void write(String str, int off, int len)Write part of a string

The use of 🛵 OutputStreamWriter

Public static void main(String[] args) throws IOException{//a: Create OutputStreamWriter, FileOutputStream OS = new FileOutputStream("C:\Study\a.txt",true); OutputStreamWriter osw = new OutputStreamWriter(os,"utf-8"); //b: Use the write method in the OutputStreamWriter object to convert characters to bytes and store them in the buffer (encoding) osw.write(" no milk tea Programmer"); //c: Flush the bytes from the memory buffer to the file using the method flush in the OutputStreamWriter object. Osw.close (); }Copy the code

Buffer flow

Buffered streams, also known as efficient streams, are enhancements to the four basic streams.

  • Byte buffering stream: BufferedOutputStream Byte buffering output stream,BufferedInputStream byte buffering input stream.

  • Character buffer stream: BufferedReader character buffer output stream,BufferedWriter character buffer input stream.

🚦 The basic principle of buffering streams is that when a stream object is created, a built-in buffer array with a default size is created. Reading and writing from buffers reduces the number of I/OS in the system and improves read and write efficiency.

BufferedWriter

The BufferWriter write stream inherits directly from Writer and implements writing text to the character output stream, buffering characters so that characters can be efficiently written.

🏎BufferedWriterr constructor

  • BufferedWriter(Writer out)Creates a character buffer write stream based on the character write stream. The default buffer size is 8192 characters
public BufferedWriter(Writer out) {
    this(out, defaultCharBufferSize);
}
Copy the code
  • BufferedWriter(Writer out, int sz)Creates a character buffer write stream based on the character write stream and the specified buffer size
public BufferedWriter(Writer out, int sz) {
    super(out);
    if (sz <= 0)
        throw new IllegalArgumentException("Buffer size <= 0");
    this.out = out;
    cb = new char[sz];
    nChars = sz;
    nextChar = 0;
}
Copy the code

The use of 🚡 BufferedWriter

public static void main(String[] args) throws IOException {

    BufferedWriter bw = new BufferedWriter(new FileWriter("C:\Users\23190\Desktop\Study\aaa.txt"));

    bw.write("BufferedWriter");

    bw.close();

}
Copy the code

BufferedReader

BufferedReader inherits the Reader abstraction directly by reading text from the character input stream and buffering the characters so that the characters can be read efficiently.

The constructor for BufferedReader

  • BufferedReader(Reader in)Creates a default size input buffer to buffer the character input stream
public BufferedReader(Reader in) {
    this(in, defaultCharBufferSize);
}
Copy the code
  • BufferedReader(Reader in, int sz)Creates a buffered character input stream using an input buffer of the specified size of Sz
public BufferedReader(Reader in, int sz) {
    super(in);
    if (sz <= 0)
        throw new IllegalArgumentException("Buffer size <= 0");
    this.in = in;
    cb = new char[sz];
    nextChar = nChars = 0;
}
Copy the code

The usual API for BufferedReader

  • Int read() reads character data one line at a time

  • Int read(char[] cbuf, int off, int len) reads up to leng characters into the array. Returns the actual number of characters read. When the end of the file is read, returns -1.

  • String readLine() reads a line of text and returns the line, or null at the end of the file: terminates the read when a newline (‘\ n’) and the carriage return (‘\ r’) indicates that the line has been read and returns the line (without the newline and carriage return).

  • Stream

    lines() returns a Stream whose elements are the lines read from the BufferedReader.

  • The close() method: closes the resource and frees the link.

The use of BufferedReader

🌵 use Stream streams below. For more information on Stream streams, see my article ✈ JDK8 new features Stream Streams

public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("C:\Users\23190\Desktop\Study\aaa.txt")); Char [] cs = new char[1024]; int count = 0; while ((count = br.read(cs)) ! = -1) { System.out.println(new String(cs, 0, count)); } //2.2 In the second mode, read String line = null; While ((line = br.readline ()))! = null) { System.out.println(line); } Stream<String> lines = br.lines(); lines.filter((str)->{ return str.equals("ab"); }).forEach((str)->{ System.out.println(str); }); br.close(); }Copy the code

BufferedInputStream byte BufferedInputStream

A constructor

  • BufferedInputStream(InputStream in)Create a BufferedInputStream from the InputStream InputStream.
  • BufferedInputStream(InputStream in, int size)Creates a BufferedInputStream based on the InputStream InputStream and the specified buffer size.

The use of BufferedInputStream

FileInputStream fis = new FileInputStream("C:\Users\23190\Desktop\Study\a.txt"); Bis = new BufferedInputStream(fis); //b: create a BufferedInputStream; byte[] b= new byte[1024]; int i = 0; while((i=bis.read(b))! =-1){ System.out.println(new String(b)); }} fis.close();Copy the code

BufferedOutputStream byte BufferedOutputStream

A constructor

  • BufferedOutputStream(OutputStream out) creates a new BufferedOutputStream to write data to the specified underlying OutputStream.

  • BufferedOutputStream(OutputStream out, int size) creates a new BufferedOutputStream to write data to the specified underlying OutputStream at the specified buffer size.

Commonly used method

  • void flush()All bytes in the buffer are written to the file only when flush is used.
  • void write(byte[] b, int off, int len)Writes len bytes from the specified byte array, starting with offset off to the buffered output stream.
  • void write(int b) Writes the specified byte to the buffered output stream

The use of BufferedOutputStream

🪂 Usage steps:

  1. Create a character output stream FileOutputStream object with the constructor bound to the destination of the output

  2. Create a BufferedOutputStream, and pass a FileOutputStream in the constructor to make FileOutputStream more efficient

  3. Write data to an internal buffer using the write method in the BufferedOutputStream object

  4. Flush the data in the internal buffer to the file using the method Flush in the BufferedOutputStream object

  5. Release resources

Public static void main(String[] args) throws IOException {//a: Create a FileOutputStream, Fos = new FileOutputStream("C:\Users\23190\Desktop\Study\ aaA.txt "); //b: create a BufferedOutputStream, pass a FileOutputStream in the constructor, BufferedOutputStream BOS = new BufferedOutputStream(fos); Bos.write (" no milk drink Programmer".getBytes()); //c: write data to an internal buffer using the write method in BufferedOutputStream; bos.write(" no milk drink Programmer".getbytes ()); // d: flush the internal buffer to the file using the method flush in BufferedOutputStream bos.flush(); Bos.close (); }Copy the code

Serialization and deserialization

🚦 Serialization converts A Java object to a platform-independent binary stream, while deserialization restores a binary stream to its original Java object, which is easy to save to disk or transfer over the network. 🚨 Only objects of classes that implement the Serializable or Exteranlizable interfaces can be serialized and deserialized. Serializable is a tokenized interface that does not contain any methods.

Transient keyword

🚨❗ Member variables modified transient cannot be serialized

  • Transient applies only to the ordinary member fields of classes that implement the Serializable interface

  • Transient can only be used to modify ordinary member variable fields

  • Static variables cannot be serialized with or without the TRANSIENT modifier

serialization

  • java.io.ObjectOutputStream extends OutputStreamObjectOutputStreamIs a process stream that implements writing objects to a file as a stream, and its serialization is implemented bywriteObject()Method to write an instantiated object to the output stream.

🛵 Serialization examples

  • Prepare a Java class with serialization, and remember that you must implement the Serializable interface
@data public class test implements Serializable {static final Long serialVersionUID = 42L; private String name; private int age; }Copy the code

🌠 Knowledge: When our Java class implements Serializable, we find that a static final Long serialVersionUID = 42L member variable is automatically added. SerialVersionUID is a version number. The serialization run uses a version number, called serialVersionUID, associated with each serializable class, which is used during deserialization to verify that the sender and receiver of the serialized object have loaded the serializable compatible class for the object. Deserialization will result in InvalidClassException if the receiver loads the object’s class with a different serialVersionUID than the corresponding sender’s class. A serializable class can explicitly declare its own serialVersionUID(serial number) by declaring a field named “serialVersionUID” (which must be a static, final long field).

  • Serialization operation
Public static void main(String[] args) throws IOException {//(1) Create ObjectOutputStream, ObjectOutputStream OOS = new ObjectOutputStream(new) FileOutputStream("C:\Users\23190\Desktop\Study\aaa.txt")); // (2) Write oos.writeObject(new test(" no teacup ",20)); (3) Write oos.writeObject(new test(" no teacup ",20)); //(3) release resources oos. Close (); }Copy the code

deserialization

Java. IO. ObjectInputStream extends InputStreamObjectInputStream is a processing flow, achieve the object deserialization, Its deserialization is implemented by reading instantiated objects from the input stream via the readObject() method.

Prerequisites for deserialization

  • Class must implement Serializable

  • A.class file for the class must exist

🛵 Deserialization example

  • Deserialize the results of the above serialization
Public static void main(String[] args) throws IOException, ClassNotFoundException {//(1) FileInputStream ObjectInputStream ois = new ObjectInputStream(new) FileInputStream("C:\Users\23190\Desktop\Study\aaa.txt")); // (2) Read the file in which the Object is stored using the method readObject in the ObjectInputStream Object o = ois.readObject(); Oem.close (); //(3) release oem.close (); //(4) use the read object system.out.println (o.string ()); //test{name=' Programmer', age=20}}Copy the code

🏁 above is a simple introduction to the Java I/O stream, if there are mistakes, please leave a message to correct, if you think this article is helpful to you then click 😻😍