4. Special operation flow
4.1 standard I / O flow
There are two static member variables in the System class:
-
public static final InputStream in: standard input stream
Typically, the stream corresponds to keyboard input or another input source specified by the host environment or the user
-
public static final PrintStream out: standard output stream
Corresponds to the display output or another output destination specified by the host environment or the user
package com.guoba.day1224; import java.io.*; /* Standard input stream */ public class Demo01 { public static void main(String[] args) throws IOException { // InputStream is = System.in; // //// int by; //// while ((by = is.read())!= -1){ //// System.out.println((char)by); //// } // InputStreamReader isr = new InputStreamReader(is); // // BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please enter a string:"); String line = br.readLine(); System.out.println("The string you entered is:"+line); System.out.println("Please enter an integer:"); int i = Integer.parseInt(br.readLine()); System.out.println("The integer you entered is:"+i); } }
The essence of an output statement is that it is a standard output stream
- PrintStream ps = System.out;
- All methods of this class, system Out can be used
PrintStream ps = System.out; // ps.println("hello"); // ps.println(100); System.out.println("hello"); System.out.println(100);
4.2 print stream
Print stream classification:
- Byte print stream: PrintStream
- Character print stream: printwitter
Print stream features:
- It is only responsible for outputting data, not reading data
- Has its own unique method
Byte print stream:
- PrintStream(String fileName): creates a new print stream with the specified file name
public static void main(String[] args) throws IOException { PrintStream ps = new PrintStream("Basic grammar\\1.txt"); ps.write(97); ps.println(97); ps.print(97); ps.close(); }
- Write data using the method of inheriting the parent class, transcoding will be performed when viewing, and the data written using the byte specific method will be output as is
PrintWriter pw =new PrintWriter("Basic grammar\\pw.txt"); pw.print("hello"); pw.print("\r\n"); pw.print(10); pw.print("\r\n"); pw.close();
Automatically refreshes when the Boolean value is true
PrintWriter pw =new PrintWriter(new FileWriter("Basic grammar\\\\pw.txt"),true); pw.print("hello"); pw.print("\r\n"); pw.print(10); pw.print("\r\n");
Case: copying Java files (print stream improved version)
package com.guoba.day1224; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; /* Copy java files (print stream improvement) */ public class Demo03 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("Basic grammar\\ccccc.txt")); PrintWriter pw = new PrintWriter(new PrintWriter("Basic grammar\\TwoZero.txt")); String line; while ((line=br.readLine())!= null){ pw.println(line); } pw.close(); br.close(); } }
4.3 object serialization stream
>Object serialization: saving objects to disk or transferring objects over the network
>This mechanism uses a byte sequence to represent an object. The byte sequence includes: object type, object data and attribute information stored in the object
>After the byte sequence is written to the file, it is equivalent to saving the information of an object in the file
>Object deserialization: on the contrary, the byte sequence can also be read back from the file to reconstruct the object and deserialize it
To achieve serialization and deserialization, use object serialization and object deserialization streams:
-
Object serialization stream: ObjectOutputStream
- Writes the original data type and graph of the Java object to the OutputStream.
- You can use ObjectInputStream to read (refactor) objects
- Persistent storage of objects can be achieved by using streaming files.
NotSerializableException: throw a Serializable interface.
This exception may be thrown by an unimplemented class when serializing the runtime
Classes that do not implement this interface will not serialize or deserialize any state
Serializable is a tag interface that implements this kind of interface without rewriting any methods
-
Object deserialization stream: ObjectInputStream
-
Use ObjectOutputStream to write raw data and objects before deserialization
-
Construction method ObjectOutputStream (InputStream in)
-
Object readObject(): reads an object from ObjectInput
package com.guoba.day1224; import com.guoba.day1223.Student; import java.io.*; public class Demo04 { public static void main(String[] args) throws IOException, ClassNotFoundException { //serialize ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Basic grammar\\1.txt")); Student s = new Student("Social cattle",30); oos.writeObject(s);//NotSerializableException oos.close(); } }
//Deserialization ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Basic grammar\\\\1.txt")); Object readObject = ois.readObject(); Student s = (Student)readObject; System.out.println(s.getName()+","+s.getAge());
Three questions:
After serializing an object with a serialization stream, will there be a problem modifying the file to which the object belongs?
- Yes, an InvalidClassException is thrown
If something goes wrong, how to solve it?
-
Add a serialVersionUID to the class to which the object belongs
prvivate static final long serialVersionUID = 42L;
If the value of a member variable in an object does not want to be serialized, how to implement it?
- The member variable is decorated with the transient keyword. The member variable marked with the keyword does not participate in the deserialization process
4.4Properties
Overview: it is a collection class of map system
You can save to or load from a stream
As a unique method of collection:
- Object setProperty(String key,String value)
- Set the keys and values of the collection, which are of String type. The bottom layer calls the hashtable put method
- String getProperty(String key)
- Search for attributes using the key specified in this attribute list
- Set stringPropertyNames()
- Returns a non modifiable key set from the property list, where the key and its value are strings
package com.guoba.day1224; import java.util.Properties; import java.util.Set; public class Demo06 { public static void main(String[] args) { Properties prop = new Properties(); prop.setProperty("itguoba001", "Li Si"); prop.setProperty("itguoba002", "Wang Wu"); Set<String> names = prop.stringPropertyNames(); for (String key : names) { String value = prop.getProperty(key); System.out.println(key + "," + value); } } }
The combination of Properties and IO flow:
-
void load (InputStream inStream)
Read the attribute list (key and element pairs) from the input byte stream
-
void load(Reader reader)
Read the attribute list (key and element pairs) from the input character stream
-
void stroe(OutputStream out,String comments)
Write this list of Properties (key and element pairs) to this Properties table and write the output byte stream in a format suitable for using the load (InputStream) method
-
void store(Writer writer,String comments)
Write this property list to this Properties table and write the output character stream in a format suitable for using the load (Reader) method
package com.guoba.day1227; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; public class Demo01 { public static void main(String[] args) throws IOException{ //mySotre(); myLoad(); } private static void myLoad() throws IOException{ Properties prop = new Properties(); FileReader fr = new FileReader("Basic grammar\\jiehe_fuben.txt");//File read to collection prop.load(fr); fr.close(); } private static void mySotre() throws IOException { Properties prop = new Properties(); prop.setProperty("itguoba001","Ye Wen"); prop.setProperty("itguoba002","Zhang Tianzhi"); prop.setProperty("itguoba003","Wu Jing"); FileWriter fw = new FileWriter("Basic grammar\\jiehe.txt");//Save collection to file prop.store(fw,null); fw.close(); } }
Case: number of games
package com.guoba.day1227; import java.util.Random; import java.util.Scanner; public class GuessNumber { public GuessNumber() { } public static void start(){ Random random = new Random(); int number = random.nextInt(100)+1; while (true){ Scanner sc = new Scanner(System.in); System.out.println("Please enter the number you want to guess:"); int guessNumber = sc.nextInt(); if (guessNumber > number){ System.out.println("The number you guessed"+guessNumber+"Big"); }else if (guessNumber < number){ System.out.println("The number you guessed"+guessNumber+"Small"); }else { System.out.println("Congratulations, you guessed right"); break; } } } }
package com.guoba.day1227; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Properties; /* InputMismatchException Input mismatch exception, that is, the input value data type cannot match the set value data type */ public class Demo0_Test { public static void main(String[] args) throws IOException { Properties prop = new Properties(); FileReader fr = new FileReader("Basic grammar\\game.txt"); prop.load(fr); fr.close(); String count = prop.getProperty("count"); int number = Integer.parseInt(count); if (number >=3){ System.out.println("The game is over. Please recharge if you want to play( https://www.cnblogs.com/guobabiancheng/)"); }else { GuessNumber.start(); number++; prop.setProperty("count",String.valueOf(number)); FileWriter fw = new FileWriter("Basic grammar\\game.txt"); prop.store(fw,null); fw.close(); } } }
Create a game where you need to access it Txt content write count=0