Day09+10 stream related content

Day09+Day10

1, IO

IO represents Input and Output respectively. Data transmission needs to rely on flow, which can be understood as data flow.

  • According to the direction of flow, it is divided into input stream (from device to memory) and output stream (from memory to device).
  • According to the different data types, it can be divided into byte stream and character stream.

Top level parent of the stream:

Top level parent Input stream Output stream
Byte stream InputStream OutputStream
Character stream Reader Writer

2, Byte stream

No matter what kind of data transmission is embodied, the bottom layer must be byte transmission.

Byte output stream:

2.1OutputStream

‚Äč java.io.OutputStream It is the parent class of all byte output streams and an abstract class, which defines the basic methods of byte output streams.

  • public void close(): closes the output stream and releases any system resources associated with the stream. (must)
  • public void flush(): flushes the output stream and forces any buffered output bytes to be written out.
  • public void write(byte[] b): writes b.length bytes from the specified byte array to this output stream.
  • public void write(byte[] b, int off, int len): writes len bytes from the specified byte array, and outputs to the output stream from the offset off.
  • public abstract void write(int b): outputs the specified byte stream.

2.2 FileOutputStream

java.io.FileOutputStream Class is a file output stream that writes out data to a file.

There are two construction methods:

//Create as string under current path
FileOutputStream fout = new FileOutputStream("a.txt");
//Construct with file as parameter
File f= new File("a.txt");
FileOutputStream fout2 = new FileOutputStream(f);

Write out the data write(int n), write out the array write(byte[] n), write out the specified length array write (byte [] n, int off, int length), write out the newline write("\r\n")

public static void main(String[] args) throws IOException {
		//Write out the data. The default value of append is false. If you want to append and create data, it should be... ("a.txt",true);
			FileOutputStream file = new FileOutputStream("a.txt");
			file.write(97);
			byte[] s = "abcde".getBytes();
			//Write out all arrays
			file.write(s);
			//Write new line
			file.write("\r\n".getBytes());
			//Write out the byte data of three lengths in the array starting from position 0
			file.write(s, 0, 3);
			file.close();	
		}
  • Although the parameter is four bytes of type int, only one byte of information is written out.

  • After the flow operation, you must release the system resources and call the close method. Remember.

2.3 FileInputStream

java.io.FileInputStream Class is the file input stream that reads bytes from the file.

Construction method:

public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("a.txt");
		int len;
    //Read single byte
		while((len=fis.read())!=-1) {
			System.out.println((char)len);
		}
		fis.close();
		//When reading a byte array, you need to get the length of each read. If you output array b directly, for example, the length of the array is 5, this time it is read-only to 3 bytes, then there are two bytes last time, which will lead to wrong output. With len, you can guarantee how much you read and how much you output
		FileInputStream fis2 = new FileInputStream("a.txt");
		byte [] b = new byte[5];
		while((len=fis2.read(b))!=-1) {
			System.out.println(new String(b,0,len));
		}
		fis.close();
	}

When you need to open it again in the middle, it is because you have read all the previous single print, and you need to start again.

2.4 reading pictures

public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream("copy.jpg");
		FileOutputStream fos = new FileOutputStream("test.jpg");
		int len;
    //The longer the array length is, the fewer IO times and the higher the efficiency are
		byte [] b = new byte[10];
    //Read array
		while((len=fis.read(b))!=-1) {
            //Write out the array and use len to ensure the accuracy of the array
			fos.write(b,0,len);
		}
    //After reading and writing, it must be closed. The closing principle of flow: first open, then close, then open, then close. It is similar to leaving a house, first close the door in the room, and then close the door
		fos.close();
   		fis.close();
	}

3, Character stream

3.1 input stream Reader

java.io.Reader Abstract class is a super class representing all classes used to read character stream, which can read character information into memory. It defines the basic common function method of character input stream.

  • public void close(): closes the flow and releases any system resources associated with the flow.
  • public int read(): read a character from the input stream.
  • public int read(char[] cbuf): read some characters from the input stream and store them in the character array cbuf.

3.2 FileReader

java.io.FileReader Class can read character files directly. During construction, the system's default character encoding (Windows is GBK) and default byte buffer (an array of bytes used to temporarily store data) are used.

Construct and read characters:

public static void main(String[] args) throws IOException {
    //Direct path construction
		FileReader f = new FileReader("a.txt");
		int len;
		char[] cubf = new char[10];
    //Read single character, promoted to int type
		while((len=f.read())!=-1) {
			System.out.println((char)len);
		}
		f.close();
    //Read character array
		FileReader f2 = new FileReader("a.txt");
		while((len=f2.read(cubf))!=-1) {
			System.out.println(new String(cubf,0,len));
		}
	}

3.3 FileWriter

java.io.Writer Abstract classes are superclasses that represent all classes used to write out character streams, writing out the specified character information to the destination. It defines the basic common function method of byte output stream.

  • Write method
  • void flush() flushes the buffer for the stream.
  • void close() closes the stream, but refreshes it first.
  • Construction method: directly construct with address or file
    • public FileWriter(File file)
    • public FileWriter("a.txt")
public static void main(String[] args) throws IOException {
		FileWriter fw = new FileWriter("aa.txt");
    //Write character
		fw.write('A');
    //Write string
		fw.write("Last year's Conference on Agriculture");
		String s = "Otherwise, the database of saipai toxin";
    //Write new line
		fw.write("\r\n");
    //Write out the specified position + length in the string
		fw.write(s, 1, 3);
		char[] cubf = "An array of bytes".toCharArray();
    //Write out character array
		fw.write(cubf);
    //Write out the specified position + specified length in the character array
		fw.write(cubf, 2, 2);
		fw.close();
	}

4, Buffer stream

4.1 introduction

Buffering streams are "enhancements" to input and output streams. Its basic principle is to create a built-in buffer array of default size when creating a stream object. Through buffer reading and writing, the number of system IO is reduced, so as to improve the efficiency of reading and writing.

4.2 byte buffer stream

Construction method:

BufferedInputStream bis = new BufferedInputStream(new FileInputStream("copy.jpg"));//Construction with basic input flow as parameters
BufferedInputStream bos = new BufferedInputStream(new FileInputStream("buffer.txt"));

Read efficiency comparison

public static void main(String[] args) throws IOException, ClassNotFoundException {
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream("copy.jpg"));
//			BufferedInputStream bos = new BufferedInputStream(new FileInputStream("buffer.txt"));
			int len=0;
			byte [] b = new byte[10];
			FileInputStream filein = new FileInputStream("copy.jpg");
			long time = System.currentTimeMillis();
			while((len=filein.read(b))!=-1) {}
			time =System.currentTimeMillis()-time;
			System.out.println("Read time:"+time);
			time = System.currentTimeMillis();
			while((len=bis.read(b))!=-1) {}
			time =System.currentTimeMillis()-time;
			System.out.println("Read time:"+time);
			filein.close();
			bis.close();
		}	
//Output results:192
    	3

4.4 character buffer stream

  • Construction method

    BufferedReader br = new BufferedReader(new FileReader("a.txt"));
    //Taking the basic character stream as the construction parameter is actually an "enhancement" to the basic stream
    BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt");
    
  • Unique methods

    • Read a row br.readLine();
    • Write out the row separator corresponding to the system bw.newLine();

4.5 text reading sorting analysis

Sort in ascending order according to the sequence number before the text:

3. The squire, servant Guo Youzhi, Fei Yi, Dong Yun, etc. are all good and practical. They are determined to be loyal and pure. They leave their majesty with the help of the emperor. It is foolish to think that there is no big or small thing in the palace, and to know and consult it, and then to carry it out, it will be beneficial to fill the gaps and omissions.
8. May your majesty entrust his officials with the purpose of appealing to thieves to revive the effect, if not, then he will punish his officials for their sins and accuse the spirit of the previous emperor. If there is no words of morality, you should be responsible for the slowness of your deeds, your deeds, and your permission, so as to show your guilt. Your majesty should also make his own plans, and take care of the good ways of the Suwa and the elegant words, so as to catch up with the imperial edicts of the previous emperor. I am grateful for your kindness.
4. General Xiang Chong, Xing Shujun, Xiaochang military, tried to use it in the past. The first emperor called it "NENG", which was supervised by people's opinions. It is foolish to think that if you know what is going on in the camp and consult with them, you will be able to bring peace to the battle line and gain advantages and disadvantages.
2. In the palace, they are all in one. It's not suitable for similarities and differences. If there are those who commit crimes and are loyal and benevolent, it is advisable to pay the punishment and reward of those who are discussed by the Secretary, so as to show his Majesty's justice, not to be partial, and to make the internal and external laws different.
1. Before the founding of the first emperor, the middle road collapsed. Today, in the next three points, Yizhou is suffering from weakness. This is a critical autumn. However, the ministers of the bodyguard are unremitting in the interior, and the loyal and determined people forget to be outside. They cover the special encounter of chasing the first emperor and want to report it to his majesty. It's better to be open to the public and listen to them. It's better to inherit virtue from the emperor, to be ambitious and ambitious. It's better not to belittle yourself, to misinterpret words, and to stop the road of loyal advice.
9. Stay away from me now. I don't know what to say.
6. The minister is the one who sets up his clothes, works in Nanyang, lives in troubled times, and doesn't ask for information. The first Emperor didn't mean his officials to be despicable, and he perverted himself. Three times, he considered his officials in the grass. He was grateful for the current affairs of his officials, so he allowed the first emperor to drive away. After the fall of the value, when he was appointed to the defeat of the army, he was ordered to be in danger. I have been here for 20 years.
7. The first emperor knew that his officials were cautious, so he sent his officials to deal with major issues in the face of collapse. Since I was ordered, I've been worried all night. I'm afraid that the trust will not work. I hurt the Ming Dynasty of the former Emperor, so I crossed Lu in May and went deep. Today, the South has been determined, and the armour has been sufficient. When the three armies are awarded, the north is determined to be the Central Plains. The commoners are exhausted and dull. They hustle out the traitors, revive the Han Dynasty, and return to the old capital. This minister therefore reported to the first emperor and was loyal to his majesty. As for the consideration of profit and loss, if we make full use of our loyalty, we will be responsible for your, your, and your permission.
5. Qin Xianchen, Yuan Xiaoren, the former Han Dynasty prospered; Qin Xiaoren, Yuan Xianchen, later Han Dynasty declined. When the first emperor was there, every time he talked about this with his officials, he did not fail to sigh and hate Yu Huan and Ling Yi. The attendants, ministers, long history, and soldiers, who have learned about the purity, the good and the dead, wish their majesty to believe in them, then the prosperity of the Han Dynasty can be counted on a day.

public static void main(String[] args) throws IOException, ClassNotFoundException {
    //Create buffered character input and output streams
			BufferedReader br = new BufferedReader(new FileReader("test.txt"));
			BufferedWriter bw = new BufferedWriter(new FileWriter("test2.txt"));
    //Create string collection
			ArrayList<String> list = new ArrayList<String>();
			String line =null;
    //Read in line by line and add to the set list
			while((line=br.readLine())!=null) {
				list.add(line);
			}
    //According to the first word of the string, i.e. ascending sequence number, Lambda expression is adopted
			Collections.sort(list, (o1,o2) -> o1.charAt(0)-o2.charAt(0));
    //Write the sorted list to a new txt file
			for(String s : list) {
				bw.write(s);
				bw.newLine();
			}
			bw.close();
			br.close();
		}

5, Conversion flow

5.1 role of conversion flow

Characters are stored in binary data in computer, but we can't understand binary data directly, we need to translate binary data.

From binary data - > characters that we can recognize, this process is called decoding

The process of character - > binary data is called encoding

Character Encoding: is a set of natural language character and binary number correspondence rules. For different codes, there are different rules. The rules corresponding to the codes are called character sets.

  • The same character set must be used for encoding and decoding. If a text is encoded with ACSII code, but decoded with GBK character set, it will read garbled code

5.2 InputStreamReader&&OutputStreamWriter

Construction method: take the file input stream as the construction parameter, and select the corresponding decoded character set. The default is UTF-8 encoding. Other read-write functions are the same as FileInputStream.

public static void main(String[] args) throws IOException, ClassNotFoundException {	
			InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"));
			InputStreamReader isr2 = new InputStreamReader(new FileInputStream("a.txt"),"GBK");
			InputStreamReader isr3 = new InputStreamReader(new FileInputStream("a.txt"),"UTF-8");
			int len;
			while((len=isr.read())!=-1) {
				System.out.print((char)len);
			}
			System.out.println();
			while((len=isr2.read())!=-1) {
				System.out.print((char)len);
			}
			System.out.println();
			while((len=isr3.read())!=-1) {
				System.out.print((char)len);
			}
		isr.close();
		isr2.close();
		isr3.close();
		}
//Output: kxzcln2nkldsanl of dasiondiaosniof
dasniondiaosniof In the classroom of the grand Designer kxzcln2nkldsanl
dasniondiaosniof????????????kxzcln2nkldsanl  

The structure of the output conversion stream is the same as that of the input stream. The difference is that a decoded character set is specified to read and a coded character set is specified to write.

5.3 reading and output cases of text

For example, GBK code is used to read and UTF-8 code is used to program.

public static void main(String[] args) throws IOException, ClassNotFoundException {
			InputStreamReader isr = new InputStreamReader(new FileInputStream("test.txt"),"GBK");
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("a.txt"),"UTF-8");
			int len;
			char b[] = new char[10];
			while((len=isr.read(b))!=-1) {
				osw.write(b,0,len);
			}	
			isr.close();
			osw.close();
		}
//View the converted text size and find UTF-8Code file is a little larger

5, Serialization stream

Java provides a mechanism for object serialization. An object can be represented by a sequence of bytes, which contains information such as the data of the object, the type of the object and the properties stored in the object. After the byte sequence is written out to the file, it is equivalent to persistently storing the information of an object in the file.

On the contrary, the byte sequence can also be read from the file, reconstruct the object, and deserialize it. Object data, object type and data information stored in the object can be used to create objects in memory.

There are two necessary conditions for a serialized stream:

  • Class to implement java.io.Serializable Interface. A class that does not implement this interface will not serialize or deserialize any state, and will throw a NotSerializableException
  • All properties of this class must be serializable, and properties that do not need to be serialized need to add the transient modifier
  • Construction method:
    • public ObjectOutputStream(OutputStream out)
    • public ObjectIntputStream(InputStream in)

5.1 serialization and deserialization

public class Day10 {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
        //The construction of serialization and deserialization stream
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt"));
   			//Create an object of class e
			Employee e = new Employee("ddd","aaa",7);
        //Serialize object e
			oos.writeObject(e);
			oos.close();
        //Deserialize Object e, because after reading the Object, it becomes the Object class and needs to be shaped downward
			Employee object = (Employee)ois.readObject();
			object.addressCheck();	
		}		
	}
class Employee implements java.io.Serializable{
	public String name;
	public String address;
	public int eid;
    //Transient member variable, not serialized
	public transient int member;
    //Add a version number to verify whether the serialized object and the corresponding class match the version
	private static final long serialVersionUID = 1L;
	public Employee(String name, String address, int eid) {
		super();
		this.name = name;
		this.address = address;
		this.eid = eid;
	}
	public void addressCheck() {
		System.out.println("Employee [name=" + name + ", address=" + address + ", eid=" + eid+ "]");
	}
		
}
  • For a JVM to deserialize an object, it must be a class that can find the class file. If the class file of the class cannot be found, a ClassNotFoundException exception is thrown.

  • When the JVM deserializes the object, it can find the class file, but the class file has been modified after the object is serialized, so the deserialization operation will fail, and an InvalidClassException exception will be thrown. This is due to:

    • The serial version number of the class does not match the version number of the class descriptor read from the stream

    • Contains unknown data type

    • No accessible nonparametric construction

5.1 exercise

  1. Save the collection serialization operation with multiple custom objects to list.txt File.
  2. Deserialization list.txt , and traverse the collection to print the object information.
//The Employee class is the same, no more
public static void main(String[] args) throws IOException, ClassNotFoundException {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.txt"));
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.txt"));
			ArrayList<Employee> list = new ArrayList<Employee>();
			//Create Employee class object
			Employee e = new Employee("first","diyi",1);
			Employee e2 = new Employee("second","dier",2);
			Employee e3 = new Employee("third","disan",2);
			//Add objects to collection
			Collections.addAll(list, e,e2,e3);
			//Serialize collection
			oos.writeObject(list);
			oos.close();
			//Deserialization set merge output
			ArrayList<Employee> list2 = (ArrayList<Employee>)ois.readObject();
			for(Employee ee: list2) {
				ee.addressCheck();
			}
		}

6, Print stream

Usually, we print output on the console by calling the print method and println method, both of which are from the java.io.PrintStream Class, which can easily print values of various data types, is a convenient way of output.

6.1PrintSystem class

  • Construction method: public PrintStream(String filename)
public static void main(String[] args) throws IOException, ClassNotFoundException {
    //Creates an object for the plot stream, overwriting the file
			PrintStream ps = new PrintStream("a.txt");
    //take System.out.println Target changed from console to file associated with ps object
			System.setOut(ps);
			System.out.println("6666667 Planned Sa..**77");
		}

Features: it can print various types of data

7, Exception handling of IO

7.1 handling before JDK

In the form of try catch finally, the flow must be closed.

public static void main(String[] args) throws IOException {
		FileWriter fw = null;
		try{fw = new FileWriter("aa.txt");
		fw.write('A');}
		catch(IOException e) {
			System.out.println("Got it");
		}
		finally{
            if(fw != null){
			fw.close();}
		}	
	}
}

7.2 handling of JDK7

JDK7 optimized try with resource statement, which ensures that each resource is closed at the end of the statement. The so-called resource refers to the object that must be closed after the program is completed.

public static void main(String[] args)  {
try(FileWriter fw = new FileWriter("aa.txt");
   FileWriter fw2 = new FileWriter("bb.txt");
   ){
		fw.write('A');
		fw2.write('Q');				}
		catch(IOException e) {
			System.out.println("Got it");
		}
}//That is, put the statement that creates the stream object in try (). If there are multiple statements, separate them with semicolons

7.3 handling of jdk9

The improvement of try with resource in JDK9 supports a more concise way of introducing objects. The imported object can also be closed automatically without manual close. Let's learn about the format.

public static void main(String[] args)  {
    FileWriter fw = new FileWriter("aa.txt");
   FileWriter fw2 = new FileWriter("bb.txt");
try(fw; fw2 ){
		fw.write('A');
		fw2.write('Q');				}
		catch(IOException e) {
			System.out.println("Got it");
		}
}//That is, just put the created stream object in try()

8, Property set

java.util.Properties Inherited from Hashtable to represent a persistent property set. It uses key value structure to store data, and each key and its corresponding value is a string.

Basic methods:

  • public Properties(): create an empty property list.

  • public Object setProperty(String key, String value): save a pair of properties.

  • public String getProperty(String key): searches for property values using the key specified in this property list.

  • Public set < string > stringpropertynames(): a collection of names of all keys.

public static void main(String[] args) throws  {
		Properties p = new Properties();
		p.setProperty("A key", "A value");
		System.out.println(p.getProperty("A key"));//Output: a value
   		System.out.println(p);
		Set<String> s = p.stringPropertyNames();
		}

In particular, it can be used with streams:

  • public load(InputStream in)

Loading the information of an input stream, corresponding to a text, enables the attribute set to load the data in the text, provided that the format of the data in the text must be in the form of key value pairs, which can be separated by symbols such as spaces, equal signs, colons, etc.

public static void main(String[] args) throws IOException {
		Properties p = new Properties();
		p.load(new FileInputStream("KV.txt"));
		Set<String> s= p.stringPropertyNames();
		for(String ss : s) {
		System.out.println(s+p.getProperty(ss));
		}
	}

Output:

???filename-KV.txt
date-2020.6.3
time-1531

Tags: Java encoding jvm Windows

Posted on Tue, 23 Jun 2020 05:54:04 -0400 by adksga