Day 31 of learning Java -- byte stream of IO framework

Keywords: Java JavaEE Attribute

Concept of stream, classification of stream, byte stream, serialization

15. I/O framework

15.1 concept of flow

  • Concept: channel between memory and storage device for data transmission
  • If the water is equivalent to data, the pipeline that transmits the water is equivalent to flow;
  • Water transmission by pipeline; data transmission by stream;

15.2 classification of flows

15.2.1 flow classification (direction)

According to the direction [key points]:

  • Input stream: read the contents of the storage device into the memory;

  • Output stream: write the contents of < memory > to < storage device >;

15.2.2 flow classification (unit, function)

Per unit:

  • Byte stream: in bytes, all data can be read and written;
  • Character stream: in characters, only text data can be read or written;

By function:

  • Node flow: it has the function of reading and writing the actual transmission data;
  • Filter flow: enhance function based on node flow;

15.3 byte stream

15.3.1 parent class of byte stream

Parent class of byte stream (abstract class):

  • InputStream: byte input stream
    public int read(){}
    public int read(byte[] b){}
    public int read(byte[] b , int off , int len){}

  • OutputStream: byte output stream
    public void write(int n){}
    public void write(byte[] b){}
    public void write(byte[] b , int off , int len){}

15.3.2 byte node stream

FileOutputStream:

  • public void write(byte[] b) / / write multiple bytes at a time, write all bytes in the B array to the output stream
import java.io.FileOutputStream;
import java.io.IOException;

public class TestFileOutPutStream {

	public static void main(String[] args) throws IOException {
		//1. Output byte stream
		//2. the output byte node stream has the function of actual data transmission (file path, boolean append) true means that the append does not overwrite
		//The path is correct: if the file does not exist, a file will be created automatically, but the directory and drive letter should be in advance
		FileOutputStream fos = new FileOutputStream("D:\\JAVAEE\\Study\\Study\\com\\qf\\Day31\\test.txt");

		//Relative path: "Files\test.txt" and the previous formal level, relative to the path of the current project, find the path and file
//		FileOutputStream fos = new FileOutputStream("Files\\test.txt");
		
		fos.write(65);
		fos.write(66);
		fos.write(67);
		fos.write('D');
		
		byte[] bytes = new byte[] {65,66,67,68,'G'};
//		fos.write(bytes); / / output a set of bytes at a time
		
		//		Byte array start subscript length
		fos.write(bytes, 1, 3);
		
//		String s = "you";
//		byte[] bs = s.getBytes();
//		System.out.println(bs[0] +"\t"+bs[1]);
//		fos.write(bs);
		
		fos.close();
	}

}

After running, the file creation and data writing are completed.

FileInputStream:

  • public int read(byte[] b) / / read multiple bytes from the stream, store the read contents in the B array, and return the actual number of bytes read; if the end of the file is reached, return - 1;
import java.io.FileInputStream;
import java.io.IOException;

public class TestFileInputStream {
	public static void main(String[] args) throws IOException {
		
		FileInputStream fis = new FileInputStream("D:\\JAVAEE\\Study\\Study\\com\\qf\\Day31\\test.txt");

		
		//Reading - 1 means the end of the file
//		while(true) {
//			int n = fis.read(); / / read one byte at a time
//			if(n == -1) {/ / end of file
//				break; / / stop reading
//			}
//			System.out.println((char)n);
//		}
		
		byte[] bytes = new byte[4];//This array is used as the storage when reading
		while(true) {
			int count = fis.read(bytes);//Number of valid bytes read each time
			if(count == -1) {
			break;
			}
			//How many to read and how many to print
			for(int i = 0 ; i < count ; i++) {
				System.out.println((char)bytes[i]+"\t");
			}
			System.out.println();
		}
		
		fis.close();
		
	}

}

Input results:

A	
B	
C	
D	

B	
C	
D	
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestFileIO {

	public static void main(String[] args) throws IOException {
		// Upload a specified picture to the project
		
		//The file is written to the storage device when it is read to the program
		
		FileInputStream fis = new FileInputStream("C:\\Users\\xuhao\\Desktop\\Qian Feng Education Java2002 Anti war squad (20200203)\\Punch the clock\\Sixth weeks\\26\\Blog.png");

		//223KB
		//Too large or too small buffer space is easy to have small problems
//		byte[] cache = new byte[1024*223];
		
//		fis.read(cache);
		
		//Output stream
		FileOutputStream fos = new FileOutputStream("Files\\Blog.png");
		
//		fos.write(cache);
		
		int len = 0;//Represents bytes read at a time
		
		while((len = fis.read()) != -1) {//As long as you don't read - 1
			fos.write(len);//How much do you read and write
		}
		
		
		fis.close();
		fos.close();
	}

}

15.3.3 byte filter stream (buffer stream)

BufferedOutputStream / BufferedInputStream

  • Improve IO efficiency and reduce the number of disk accesses;
  • The data is stored in the buffer. flush writes the contents of the buffer to the file, or it can be close d directly;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestBufferOutput {

	public static void main(String[] args) throws IOException {
		
		//A byte output node stream is required for parametric construction
		//Create byte output node stream first
		FileOutputStream fos = new FileOutputStream("Files/buff.txt");
		
				//Enhance node flow	
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		
		bos.write('A');
		bos.write('B');
		
		bos.flush();//Flush buffer (writes data from the buffer to a file at once and clears the current buffer)
		
		bos.write('C');
		bos.write('D');
		
		bos.close();//The cascade executes flush(); while releasing resources, it writes the buffer data to the file at one time
	
		
		//-----------------------------------------
		
		FileInputStream fis = new FileInputStream("Files/buff.txt");
		
		BufferedInputStream bis = new BufferedInputStream(fis);
		
		byte[] bytes = new byte[100];
		int count = bis.read(bytes);
		
		for(int i = 0 ; i < count ; i++) {
			System.out.println(bytes[i]);
		}
	}

}

Output results:

65
66
67
68

15.3.4 byte filter stream (object stream)

Object stream: ObjectOutputStream / ObjectInputStream

  • Enhanced buffer function;
  • Enhanced the function of reading and writing 8 basic data types and strings
  • Enhanced read and write object capabilities:
    readObject() reads an object from the stream;
    writeObject(Object obj) writes an object to the stream

The process of using streaming objects is called serialization and deserialization;

15.3.5 object serialization

Details of object serialization:

  • Must implement Serializable interface;
  • All its properties must be serializable;
  • transient is modified as a temporary attribute and does not participate in serialization;
  • Flag read to the end of the file: java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

public class TestObjectStream {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		OutputStream os = new FileOutputStream("Files/obj.txt");
		
		ObjectOutputStream oos = new ObjectOutputStream(os);
		
	//	oos.writeInt(60);
		
	//	oos.writeDouble(6.6);
		
	//	oos.writeBoolean(true);
		
		Student stu1 = new Student("Tom" , 22 , "male" , 99D , new Address());
		Student stu2 = new Student("Jack" , 21 , "male" , 95D , new Address());
		Student stu3 = new Student("Rose" , 20 , "female" , 99D , new Address());
		
		oos.writeObject(stu1);
		oos.writeObject(stu2);
		oos.writeObject(stu3);
		
		oos.flush();
		
		//------------
		InputStream is = new FileInputStream("Files/obj.txt");
		ObjectInputStream ois = new ObjectInputStream(is);
		
//		int result = ois.readInt();
//		System.out.println(result);
		
//		Object obj1 = ois.readObject();
//		System.out.println(obj1);
//		Student s = (Student)obj1;
//		System.out.println(s.name);
		
//		Object obj2 = ois.readObject();
//		System.out.println(obj2);
		
//		Object obj3 = ois.readObject();
//		System.out.println(obj3);
		
		while(true) {
			try {
				Object obj = ois.readObject();
				System.out.println(obj);
			}catch(Exception e) {
				//Get the EOFException at the end of the file once and stop the loop
				break;//Custom handling exception
			}
		}
	}

}

//Object to support serialization
//Property also supports serialization
class Student implements Serializable{//If the interface has been serialized and the static decorated value is serialized, then the value belongs to all classes and affects serialization
	String name;
	Integer age;
	String sex;
	Double score;
	Address add;	
	
	//Attribute decorated by transient, does not participate in serialization
	
	//Array of basic data types, serializable
	//Array of reference data type, array type should support serialization
	
	public Student(String name, Integer age, String sex, Double score, Address add) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.score = score;
		this.add = add;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", sex=" + sex + ", score=" + score + ", add=" + add + "]";
	}
	
}

class Address implements Serializable{
	String position;
	String zipCode;
	public Address() {}
	public Address(String position, String zipCode) {
		super();
		this.position = position;
		this.zipCode = zipCode;
	}
	
}

Output results:

Student [name=Tom, age=22, sex=male, score=99.0, add=com.qf.Day31.Address@b4c966a]
Student [name=Jack, age=21, sex=male, score=95.0, add=com.qf.Day31.Address@2f4d3709]
Student [name=Rose, age=20, sex=female, score=99.0, add=com.qf.Day31.Address@4e50df2e]
Published 44 original articles, won praise 14, visited 2250
Private letter follow

Posted by kenrbnsn on Mon, 16 Mar 2020 06:44:14 -0700