Note: this chapter is used to review the knowledge of exception, IO stream and serialization.
1, Abnormal
Exceptions are objects used to encapsulate error information; It consists of three parts: exception type, prompt information and error line number prompt;
1. Abnormal architecture
Level 1: top level parent class Throwable
Layer 2: Error and Exception
Error: an error class, which indicates an internal system error or resource exhaustion error that cannot be recovered immediately after the repair program itself Executed. Subclasses include IOError and awtiror
Exception: exception class, which indicates the error of the program itself and compilation error (compilation error or operation error).
2. Exception handling method
When a program encounters an exception, there are usually two ways to deal with it: catch the exception or throw it up.
-
Catch exception
try{
Code to capture
} catch (exception type) Exception name)
Treatment scheme
}
-
Throw scheme
For exceptions that you don't want to handle or can't handle now, you can choose to throw up - the throw pipeline is set on the method - the throw exception type
eg: void method1() throws Exception1,Exception2{}
TIPS: there is a default exception pipeline on the method: RuntimeException
3. Difference between throws and throw
throws: used at the method declaration, followed by the name of the exception, indicating that this method will throw exceptions, and the caller of this method needs to handle these exceptions.
Throw: used inside a method, followed by the name of the exception object, indicating that an exception is thrown here and handled by the statement in the method body. (exception must be thrown when throw is executed)
/**This class is used for introductory cases of exceptions*/ public class ExceptionDemo { public static void main(String[] args) { // method1();// Call the method used to expose the exception //method2();// Call exception solution 1 -- capture processing -- solve it yourself //method3();// Call exception solution 2 -- throw it up -- solve it by others f(); //f2(); f3(); /**1.10/0 * --Error ArithmeticException * 2.10/3.5 * --Error inputmismatch exception -- input mismatch exception * */ /**1.Don't be afraid of bugs. Real warriors dare to face the bugs they write; * 2.Learn to read the wrong information in the newspaper and determine your wrong direction; * 3.Learn to read the wrong line number prompt, and determine the position of your error report and where it is wrong * Note: the source code will not report errors. It depends on the code you write * */ /**Format of exception throwing: write the throws exception type between the braces and braces of the method * If there are multiple exceptions, separate them with commas * * If a method throws an exception, whoever calls the method needs to handle the exception * There are also two options for processing here: capture solution or continue to throw up * * Note: we usually deal with the exception thrown by the method before calling the method by main() * Instead of throwing the problem to main(), because the JVM calls main(), and no one solves it later. Should an error be reported or an error be reported * */ } private static void f3() { try{ f2(); }catch (Exception e){ System.out.println("Solution~"); } } //Continue to throw exceptions upward - others solve them private static void f2()throws Exception { System.out.print("Please enter the first integer to calculate:"); int a = new Scanner(System.in).nextInt(); System.out.print("Please enter the second integer to calculate:"); int b = new Scanner(System.in).nextInt(); System.out.println(a/b); } private static void f() { try{ method3(); }catch (Exception e){ System.out.println("Solution~"); } } private static void method3()throws Exception { System.out.print("Please enter the first integer to calculate:"); int a = new Scanner(System.in).nextInt(); System.out.print("Please enter the second integer to calculate:"); int b = new Scanner(System.in).nextInt(); System.out.println(a/b); } /* try{ Possible exception code thrown }catch(Type of exception (name of exception){ In case a preset exception is caught, the solution is to handle it } **/ private static void method2() { try{ System.out.print("Please enter the first integer to calculate:"); int a = new Scanner(System.in).nextInt(); System.out.print("Please enter the second integer to calculate:"); int b = new Scanner(System.in).nextInt(); System.out.println(a/b); }catch (ArithmeticException e){ System.out.println("Divisor cannot be 0"); }catch (InputMismatchException e){ System.out.println("Please enter the specified integer!"); /**Using the idea of polymorphism, no matter what the child Exception is, it is uniformly regarded as the parent type Exception * Make more general solutions. You can even write only this one, but not the above two*/ }catch (Exception e){ System.out.println("The data entered is incorrect, please re-enter~~"); } } }
2, IO stream
8.1 classification of flow:
The unit of transmission processing according to the stream: byte stream Character stream
According to the direction of the flow: enter the flow Output stream
-
Byte input stream InputStream --- Abstract parent, cannot be instantiated
FileInputStream --- the byte input stream of the operation File. The structure should be: File / path
BufferdInputStream: efficient byte input stream. Construction method: InputStream
-
Byte output stream OutputStream --- Abstract parent, unable to instantiate
FileOutputStream --- byte output stream of operation file. Constructors include (File), (File, boolean append) and (string) name),(String name, boolean append)
Note: all four can override the output;
BufferedOutputStream ---- efficient byte output stream. The structure should be: OutputStream
-
Character input stream Reader --- Abstract parent, cannot be instantiated
FileReader --- the character input stream of the operation File. The structure should be: File / path
BufferedReader --- efficient character input stream, constructed as Reader
-
Character output stream Writer --- Abstract parent, cannot be instantiated
FileWriter --- the character output stream of the operation file. The structures are: (File), (File, boolean append) and (string) name),(String name, boolean append)
BufferedWriter --- efficient character output stream, constructed as: Writer
import java.io.*; /**This class is used to test byte input streams*/ public class TestIn { public static void main(String[] args) { method(); method2(); } private static void method2() { FileInputStream in = null; try { in = new FileInputStream("D:\\ready\\1.txt"); int b; while ((b = in.read()) != -1){ System.out.println(b); } } catch (Exception e) { e.printStackTrace(); }finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void method() { //InputStream in = new InputStream(); -- Abstract parent cannot be instantiated FileInputStream in = null; try { in = new FileInputStream(new File("D:\\ready\\1.txt")); // System.out.println(in.read());//97 // System.out.println(in.read());//98 // System.out.println(in.read());//99 // System.out.println(in.read());//-1 //Requirement: all contents in the file need to be read circularly until it is finished //Define variables and save the read data int b; while (( b = in.read()) != -1){//As long as the read data is not - 1, there is still data System.out.println(b);//Print the data read in the current cycle } //Closed flow } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); /**finally{}The code block is the third part of the try catch result * This part, whether or not an exception is caught, will eventually be executed * In other words, this is a code block that must be executed, which is often used for flow closure operations*/ }finally { //Close flow - the flow object must be released after use! try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } /*********************************************************************/ import java.io.*; /**This class is used to test byte output streams*/ public class TestOut { public static void main(String[] args) { // method1(); / / used to test normal byte output stream method2();//Used to test efficient byte output stream } private static void method2() { BufferedOutputStream out = null; try { // out = new BufferedOutputStream(new FileOutputStream("D:\\ready\\1.txt")); out = new BufferedOutputStream( new FileOutputStream(new File("D:\\ready\\1.txt"),true)); out.write(99); out.write(99); out.write(99); }catch (Exception e){ e.printStackTrace(); }finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void method1() { FileOutputStream out = null; try { // out = new FileOutputStream(new File("D:\\ready\\1.txt")); out = new FileOutputStream("D:\\ready\\1.txt",true); out.write(97); out.write(98); out.write(99); } catch (Exception e) { e.printStackTrace(); }finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
/**This class is used to test character input streams*/ public class TestIn2 { public static void main(String[] args) { method1();//Normal input stream read method2();//Efficient input stream reading } private static void method2() { BufferedReader in1 = null; try { in1 = new BufferedReader( new FileReader("D:\\ready\\1.txt")); int b; while((b = in1.read())!= -1){ System.out.println(b); } } catch (Exception e) { e.printStackTrace(); }finally { try { in1.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void method1() { FileReader in = null; try { //FileReader in2 = new FileReader(new File("D:\\ready\\1.txt")); in = new FileReader("D:\\ready\\1.txt"); int b; while((b = in.read())!= -1){ System.out.println(b); } } catch (Exception e) { e.printStackTrace(); }finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } /*******************************************************************/ /**This class is used to test character output streams*/ public class TestOut2 { public static void main(String[] args) { //method1(); / / used to test the normal character output stream method2();//Used to test efficient character output stream } private static void method2() { BufferedWriter out2 = null; try { // out2 = new BufferedWriter(new FileWriter("D:\\ready\\1.txt")); out2 = new BufferedWriter(new FileWriter(new File( "D:\\ready\\1.txt"),true)); // out2 = new BufferedWriter(new FileWriter("D:\\ready\\1.txt",true)); out2.write(98); out2.write(98); out2.write(98); } catch (IOException e) { e.printStackTrace(); }finally { try { out2.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void method1() { FileWriter in = null; try{ in = new FileWriter("D:\\ready\\1.txt"); in.write(97); in.write(97); in.write(97); }catch(Exception e){ e.printStackTrace(); }finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
3, Serialization and deserialization
1. General
Serialization: save the information of the object to a file -- ObjectOutputStream
Deserialization: ObjectInputStream deserializes and reconstructs the basic files and objects written by the previously used ObjectOutputStream.
- Prepare the Student class. Note: you need to implement a serializable interface
- Create a serialized stream object;
- Create a student class object that is serialized and output;
- Use stream object
Note: the custom class needs to override toString() to view the properties and property values of the object. Otherwise, the address value will be printed.
How does deserialization succeed?
Core: the UID in the Student class is consistent with the UID in the deserialization stream.
- One serialization corresponds to one serialization; [recommended]
- After one serialization, the contents in the Student are not modified, and then deserialized;
- Write the UID in the Student as a fixed value;
Note: when the UID held by the deserialization stream is inconsistent with the UID in the Student class, deserialization will fail -- - eg: use the automatically generated UID, serialize first, modify the Student, and then deserialize, which will fail.
2 serialized application scenarios
- The files to be serialized must implement the Serializable interface to start the serialization function;
- Data that does not need to be serialized can be modified into static. Reason: static resources belong to class resources and are not output with the object being serialized;
- Each serialized file has a unique id. if this id is not added, the compiler will automatically generate one according to the class definition information;
- During deserialization, if it is inconsistent with the serialized version number, deserialization cannot be completed;
- Commonly used data transmission with the server, serialization into files, deserialization and reading data;
- Socket stream is often used to transfer objects between hosts;
- Data that does not need to be serialized can be modified as transient. It only exists in memory during program operation and will not be serialized and persisted.
import java.io.*; /**This class is used to test serialization and deserialization * Serialization: * It refers to the permanent storage of Java objects in the program on disk, * It is equivalent to the written process. The direction is out, and the corresponding stream is ObjectOutputStream * Deserialization: * It refers to the process of reading / restoring the data stored in the serialized file to the Java program * The direction is in and the corresponding flow is ObjectInputStream * * */ public class TestSerializeable { public static void main(String[] args) { method1();//Complete serialization method2();//Deserialization complete } private static void method2() { ObjectInputStream in = null; try{ in = new ObjectInputStream( new FileInputStream("D:\\ready\\1.txt")); System.out.println(in.readObject()); System.out.println("Deserialization succeeded~~~"); }catch(Exception e){ System.out.println("Deserialization failed~~~"); e.printStackTrace(); }finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } /**Serialization method*/ private static void method1() { //1. Declare a local variable that takes effect in this method. The local variable does not need to be initialized ObjectOutputStream out =null; //2. Since IO operations may throw exceptions, you need to complete the try catch structure try{ //Create flow object out = new ObjectOutputStream( new FileOutputStream("D:\\ready\\1.txt")); //Specifies the object to serialize Student obj = new Student("Spongebob",3,"in the sea",'male'); out.writeObject(obj); System.out.println("Serialization succeeded~"); }catch (Exception e){ System.out.println("Serialization failed~~"); e.printStackTrace(); }finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }