Transform stream, print stream, serialization, deserialization, file operation (File)

Keywords: Java Eclipse

A conversion flow

1.1 classification

Input stream

Output stream

InputStreamReader

OutputStreamWriter

1.2 features

  Conversion stream refers to the conversion of bytes to character stream, mainly including InputStreamReader and OutputStreamWriter

        one    InputStreamReader is mainly used to convert byte input stream into character input stream

        two   OutputStreamWriter mainly converts byte stream output stream into character output stream

1.3 InputStreamReader

classification

method

describe

Construction method

InputStreamReader(InputStream in)
InputStreamReader(InputStream in,Charset cs)
InputStreamReader(InputStream in,CharsetDecoder dec)
InputStreamReader(InputStream in,String charsetName)

Create an object that uses the default character set
Create the object using the given character set
Create this object using the given character set decoder
Creates the object using the specified character set

common method

void close()
String getEncoding()
int read()
int read(char[] cbuf, int offset, int length)
boolean ready()

Close the flow and release all resources associated with it
Returns the name of the character encoding used by this stream
Read single character
Reads a character into a part of an array
Determine whether the stream is ready for reading

code:

public class IO_01_InputStreamReader {
	public static void main(String[] args) {
		String file="./input.txt";
		//Byte stream
		try (FileInputStream fis=new FileInputStream(file);
				//Conversion flow
				InputStreamReader isr=new InputStreamReader(fis);
				//Buffer stream
				BufferedReader br=new BufferedReader(isr);			
				){
			String temp=null;
			while((temp=br.readLine())!=null){
				System.out.println(temp);
			}
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
}

Second print stream

2.1 features

one   Print stream is the most convenient class for output

two   Contains byte print stream PrintStream and character print stream PrintWriter

three   PrintStream is a subclass of OutputStream. After an instance of an output stream is passed to the print stream, the content can be output more conveniently, which is equivalent to repackaging the output stream

four   The print() method of PrintStream class is overloaded many times. print(int i), print(boolean b), print(char c)

Code 1:  

public class IO_02_PrintStream {
public static void main(String[] args) {
	String file="./input.txt";
	try (
			// Create byte output stream
			FileOutputStream fos = new FileOutputStream(file);
			// Encapsulate as print stream
			PrintStream ps = new PrintStream(fos);
			){
		// Call method to print
		ps.println();
		ps.println("how are you");
		ps.println(false);
		ps.println(123123);
		
		// Use the print stream provided by the System and print to the console by default
		System.out.println("In execution....");
		// Change print position
		System.setOut(ps);
		// Print to the specified location, no longer to the console
		System.out.println("Test 1");
		System.out.println("Test 2");
		System.out.println("Test 3");
		System.out.println("Test 4");
		System.out.println("Test 5");
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}
}

Function: print the contents of a.txt file in disk D to a.txt file in disk E by print stream

The code is as follows:

package day02;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class IO_03_PrintStream {
	public static void main(String[] args) {
				//Create byte input stream
		try (FileInputStream fis = new FileInputStream("D:/a.txt");
				//Create character output stream
				FileOutputStream fos = new FileOutputStream("E:/a.txt");
				// Encapsulate as print stream
				PrintStream ps = new PrintStream(fos);) {
			System.setOut(ps);
			byte[] bytes = new byte[fis.available()];
			int count = 0;
			while ((count = fis.read(bytes)) != -1) {
				System.out.println(new String(bytes, 0, count));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("===");
	}
}

III. serialization and deserialization

3.1 concept

  Serialization: ObjectOutputStream saves objects to hard disk  
  Deserialization: ObjectInputStream loads the objects in the hard disk into memory

3.2 method of creating object

1 new uses the most
2 reflection mechanism
3 clone cloning is obsolete and replaced by deserialization
4 deserialization

3.3 purpose

Purpose: long term storage, object transfer

3.4 application scenarios

Serialization is to convert data objects into binary streams, so that data persistence and network transmission can be carried out
If the object is not serialized, there is no way to store and pass it
Deserialization is the reverse processing of serialization

3.5 process

Data object -- > serialization -- > binary stream -- > encryption processing -- > network delivery -- > decryption processing -- > deserialization -- > data object

If an object wants to be serialized, the class must implement the Serializable interface, which has no method function and is just a tag

Code implementation:

1 create an object

package day02;

import java.io.Serializable;

public class User implements Serializable {

	/**
	 * If you don't add, every time you change the class, the UID changes and needs to be serialized again
	 * 
	 * Objective: to control the version of the serialized object. If the new version is compatible with the old version, this value does not need to be changed. If it is incompatible, change the value, and the original serialized object cannot be used
	 * 
	 * Version number
	 */
	private static final long serialVersionUID = 1L;
	private String name;
	/**
	 * transient : The attribute value of the variable modified with it will not be serialized. Unnecessary data can be discarded to improve the efficiency of serialization and deserialization
	 */
	private transient int age;

	public void m1() {
		System.out.println("===");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	// 8295929167632747574
	// 6221260663931743134
	public User(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [name=" + name + ", age=" + age + "]";
	}

}

2 object serialization:

public class IO_04_ObjectOutputStream {
	public static void main(String[] args) throws Exception {
		User user = new User("Zhang San", 18);
		// Create output stream
		FileOutputStream fos = new FileOutputStream("D:/d");
		// Create object flow
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		// Write out object
		oos.writeObject(user);
		// Brush cache, turn off resources
		oos.flush();
		oos.close();
	}
}

3 deserialization

package day02;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class IO_05_ObjectInputStream {
	public static void main(String[] args)  throws Exception{
      //Create input stream
		FileInputStream fis = new FileInputStream("D:/d");
        // Create object flow
		ObjectInputStream ois = new ObjectInputStream(fis);
		Object o = ois.readObject();
		System.out.println(o);
		User user = (User)o;
		user.m1();
	}
}

         

Posted by dave914 on Thu, 28 Oct 2021 04:27:18 -0700