Java self study note Day22

Posted by levi_501_dehaan on Thu, 28 Nov 2019 22:35:04 +0100

Day22 (other IO streams)

Sequence stream

Sequence flow overview (understanding)

A:What is sequence flow
	*Sequence stream can integrate multiple byte input streams into one,Reading data from the sequence stream is,Will start with the first flow of the entire sum,Read one and go on to the next
B:Usage mode:
	*Integrate two:SequenceInputStream(InputStream,InputStream)
	
public static void demo2() throws FileNotFoundException, IOException {
		FileInputStream fis1 = new FileInputStream("a.txt");
		FileInputStream fis2 = new FileInputStream("b.txt");
		SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
		FileOutputStream fos = new FileOutputStream("c.txt");

		int b;
		while ((b = sis.read()) != -1) {
			fos.write(b);
		}

		sis.close(); // When sis is closed, it will also close the flow objects passed in the construction method
		fos.close();
	}	

Sequence flow integration multiple (understanding)

* Integrate multiple input streams
	 * SequenceInputStream(Enumeration<? extends InputStream> e)
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// demo1();
		// demo2();
		FileInputStream fis1 = new FileInputStream("a.txt");
		FileInputStream fis2 = new FileInputStream("b.txt");
		FileInputStream fis3 = new FileInputStream("c.txt");

		Vector<FileInputStream> v = new Vector<>(); // Create collection object
		v.add(fis1); // Store stream objects in
		v.add(fis2);
		v.add(fis3);

		Enumeration<FileInputStream> en = v.elements();
		SequenceInputStream sis = new SequenceInputStream(en); // Integrate the input streams in enumeration into one
		FileOutputStream fos = new FileOutputStream("d.txt");

		int b;
		while ((b = sis.read()) != -1) {
			fos.write(b);
		}

		sis.close();
		fos.close();
}

Memory output stream (Master)

/*
A:What is memory output stream
	*The output stream can write data to the memory and treat the memory as a buffer. After writing out, all data can be obtained at one time
B:Usage mode
	*Create object: new ByteArrayOutputStream / / essentially equivalent to array, invalid when turned off
	*Write out data: write(int),write(byte [])
	*Get data: toByteArray()
C:Case demonstration
	 * FileInputStream There was a garbled code while reading Chinese
	 * 
	 * Solution
	 * 1,Character stream read
	 * 2,ByteArrayOutputStream
	 * @throws IOException 
 */
	public static void main(String[] args) throws IOException {
		//demo1();
		FileInputStream fis = new FileInputStream("e.txt");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();			
		//Created a memory array that can grow in memory
		
		int b;
		while((b = fis.read()) != -1) {
			baos.write(b);													
			//Write the read data to memory one by one
		}
		
		//byte[] arr = baos.toByteArray();									
		//Get all the data in the buffer and assign it to the arr array
		//System.out.println(new String(arr));
		
		System.out.println(baos.toString());							
        //Convert the contents of the buffer to a string. You can omit calling toString method in the output statement
		fis.close();
	}

Practice

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @param args
 * Define a file input stream, call read(byte[] b) method, and print out the contents of a.txt file (byte array size is limited to 5)
 * 
 * Analysis:
 * 1,read(byte[] b)It is the method of byte input stream. Create FileInputStream and associate with a.txt
 * 2,Create a memory output stream and write the read data to the memory output stream
 * 3,Create byte array with length of 5
 * 4,Convert all data of memory output stream to string printing
 * 5,Close input stream
 * @throws IOException 
 */
public class Test3 {

	public static void main(String[] args) throws IOException {
		// 1. Read (byte [] b) is the method of byte input stream. Create FileInputStream and associate a.txt
		FileInputStream fis = new FileInputStream("a.txt");
		// 2. Create a memory output stream and write the read data to the memory output stream
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// 3. Create byte array with length of 5
		byte[] arr = new byte[5];
		int len;
		
		while((len = fis.read(arr))!=-1) {
			baos.write(arr,0,len);	
		}
		//4. Convert all data of memory output stream to string printing
		System.out.println(baos.toString());
		// 5. Close the input stream
		fis.close();
	}

}

Object operation flow (understanding)

Overview of object operation process

A:What is object operation flow
	*The stream can write out an object,Or read an object into the program,That is, serialization and deserialization are performed
B:Usage mode
	//*Write out: new ObjectOutputStream(OutputStream),writeObject()
	//Object input stream, serializing
	
		public static void demo1() throws IOException, FileNotFoundException {
		Person p1 = new Person("Zhang San", 23);
		Person p2 = new Person("Li Si", 24);

		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("e.txt"));
		oos.writeObject(p1);
		oos.writeObject(p2);

		oos.close();
	}
	
	//*Read: new ObjectInputStream(InputStream),readObject()
	//Object input stream, deserialization;
	
	public static void demo1() throws IOException, FileNotFoundException,
			ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e.txt"));
		
		Person p1 = (Person) ois.readObject();
		Person p2 = (Person) ois.readObject();
		//Person p3 = (Person) ois.readObject();		
        //EOFException when the file reads to the end
		
		System.out.println(p1);
		System.out.println(p2);
		
		ois.close();
	}

Object operation process optimization

public static void main(String[] args) throws IOException {
		Person p1 = new Person("Zhang San", 23);
		Person p2 = new Person("Li Si", 24);
		Person p3 = new Person("Wang Wu", 25);
		Person p4 = new Person("Zhao Liu", 26);

		ArrayList<Person> list = new ArrayList<>();
		list.add(p1);
		list.add(p2);
		list.add(p3);
		list.add(p4);

		ObjectOutputStream oos = 
            new ObjectOutputStream(new FileOutputStream("e.txt"));
		oos.writeObject(list); // Write out the whole collection object once
		oos.close();
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e.txt"));
		ArrayList<Person> list = (ArrayList<Person>) ois.readObject();	
        //Read the collection object once
		
		for (Person person : list) {
			System.out.println(person);
		}
		
		ois.close();
}

IO stream plus id

* attention
	*The object to be written out must implement the Serializable interface to be serialized
	*No need to add id
	*The function of id number is to prompt error information

Printing flow

A:What is a print stream
	*This flow can easilytoString()Result output,And automatically add new line
	*System.out It's just one. PrintStream,It outputs information to the console by default
B:Usage mode
	*PrintStream and PrintWriter They are byte stream and character stream printed respectively
	*Printing:print(),println();
	*Automatic brush out:printWriter(OutputStream out,boolean autoFlush)
	*Print stream value operation data purpose
	
	public static void main(String[] args) throws IOException {
		PrintWriter pw = new PrintWriter(new FileOutputStream("f.txt"),true);
		//pw.println(97); / / the auto flushing function is only for the println method
		//pw.write(97);
		pw.print(97);
		pw.println(97);
		pw.close();
	}

Standard I / O stream

A:What is standard output stream input stream?
	*System.in yes InputStream,Standard input stream,Data can be read from the keyboard by default;
	*System.out yes PrintStream,Standard output stream,By default, you can Console Output characters and data in
B:Modify standard I / O flow
	*Modify input flow:System.SetIn(InputStream);
	*Modify output stream:System.SetOut(PrintStream);
	
public static void main(String[] args) throws IOException {
		System.setIn(new FileInputStream("a.txt")); // Change standard input flow
		System.setOut(new PrintStream("b.txt")); // Change dimension output flow

		InputStream is = System.in; // Get the standard keyboard input stream, point to keyboard by default, point to file after changing
		PrintStream ps = System.out; // Get the standard output stream, which points to the console by default, and points to the file after the change

		int b;
		while ((b = is.read()) != -1) {
			ps.write(b);
		}
		// System.out.println(); / / is also an output stream. Do not close it, because there is no pipeline associated with files on the hard disk
		is.close();
		ps.close();

}

Two ways to realize keyboard input

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Demo07_SystemIn {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		//demo1();
		
		Scanner sc = new Scanner(System.in);
		String line = sc.nextLine();
		System.out.println(line);
		sc.close();
	}

	private static void demo1() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));		//InputStreamReader transform stream
		String line = br.readLine();
		System.out.println(line);
		br.close();
	}

}

Practice

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;

public class Test2 {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		System.setIn(new FileInputStream("Dongyu Zhou.jpg")); // Change standard input flow
		System.setOut(new PrintStream("copy.jpg")); // Change standard output stream

		InputStream is = System.in;
		PrintStream ps = System.out;

		byte[] arr = new byte[1024];
		int len;

		while ((len = is.read(arr)) != -1) {
			ps.write(arr, 0, len);
		}

		is.close();
		ps.close();
	}

}

Random access flow

A:Random access flow overview
	*RandomAccessFile Summary
	*RandomAccessFile Class does not belong to flow,yes Object Subclasses of classes,But it's converging InputStream and OutputStream Function
	*Support random access file reading and writing
B:read(),write(),seek()

Data input and output flow

A:What is data input and output flow
	*DataInputStream,DataOutputStream Data can be read according to the size of the basic data type
	*for example:Press Long Size write an array,When writing out, this data takes up8byte,When reading, you can also follow the Long Type reading,Read once8Byte
B:Usage mode
	*DataOutputStream(OutputStream),WriteInt(),WriteLong()
public static void main(String[] args) throws IOException {
		DataInputStream dis = new DataInputStream(new FileInputStream("h.txt"));
		int x = dis.readInt();
		int y = dis.readInt();
		int z = dis.readInt();
		
		System.out.println(x);
		System.out.println(y);
		System.out.println(z);
		
		dis.close();
	}

	public static void demo3() throws FileNotFoundException, IOException {
		DataOutputStream dos = new DataOutputStream(new FileOutputStream("h.txt"));
		dos.writeInt(997);
		dos.writeInt(998);
		dos.writeInt(999);
		dos.close();
	}

Properties

Overview of Properties and use as a Map collection

A: overview of properties
	*The Properties class represents a persistent property set
	*Properties can be saved in the stream and loaded from the stream
	*Each key and its corresponding value in the property list is a string
 B: case demonstration
	*Properties as a Map collection

Properties special features

A:Properties Special functions
	*public Object setProperty(String key,String value)
	*public String getProperty(String key)
	*public Enumeration<String> StringPropertyNames()
B:Case demonstration
	*Properties Special functions of
public static void demo2() {
		Properties prop = new Properties();
		prop.setProperty("name", "Zhang San");
		prop.setProperty("tel", "18912345678");

		// System.out.println(prop);
		Enumeration<String> en = (Enumeration<String>) prop.propertyNames();
		while (en.hasMoreElements()) {
			String key = en.nextElement(); // Get each key in Properties
			String value = prop.getProperty(key); // Get value from key
			System.out.println(key + "=" + value);
		}
}

load() and store() functions of Properties

Case demonstration
public static void main(String[] args) throws FileNotFoundException, IOException {
		Properties prop = new Properties();
		prop.load(new FileInputStream("config.properties"));
        // Read the key value pair on the file into the collection
		prop.setProperty("tel", "18922345678");
		prop.store(new FileOutputStream("config.properties"), null);
		// The second parameter is the description of the list parameter, which can be given a value or null
		System.out.println(prop);
}

Topics: Java P4