@Yixian doesn't wear small shoes
1. All character streams are byte streams encapsulated by processing streams
2. Basic character stream
- Advantages: you can set the encoding of reading and writing
2.1: basic character output stream: Writer - > outputstreamwriter
eg:public static void main(String[] args) throws IOException { //Declare stream object OutputStreamWriter osw=null; try { //1. Create flow object osw=new OutputStreamWriter(new FileOutputStream("a1.txt",true), "utf-8"); //2. Write content to file with stream object osw.write("I'm Qianfeng"); osw.append("I am Chinese,"); System.out.println("Write successful"); } catch (Exception e) { e.printStackTrace(); }finally { //3. Shut off if (osw!=null) { osw.close(); } } }
2.2: basic character input stream: Reader - > inputstreamreader
eg:public static void main(String[] args) throws IOException { //Declare stream object InputStreamReader osw=null; try { //1. Create flow object osw=new InputStreamReader(new FileInputStream("a1.txt"), "utf-8"); //2. Read the contents of the file with the stream object //Prepare a character array char[] c=new char[10]; //Read once first. The read content is stored in the array, and the read length is returned int len; //Judge every time you read while ((len=osw.read(c))!=-1) { //Converts the read content into a string and outputs it String content=new String(c, 0, len); System.out.println(content); } System.out.println("Read complete"); } catch (Exception e) { e.printStackTrace(); }finally { //3. Shut off if (osw!=null) { osw.close(); } } }
3. Rich second generation character stream
- Advantages: easy to use
- Disadvantages: compilation cannot be set (if the code of the read file is different from that of the workspace, garbled code will appear)
eg:public static void main(String[] args) { //Declare stream object FileWriter fw=null; FileReader fr=null; try { //1. Create a flow object fr=new FileReader("D:"+File.separator+"Once upon a time, there was a Lingjian mountain.txt"); fw=new FileWriter("b1.txt"); //2. Read and write while streaming //Prepare an array char[] c=new char[100]; int len; //Judge every time you read while ((len=fr.read(c))!=-1) { //Each time it is read, the read content is written to the file fw.write(c, 0, len); } System.out.println("Success copy "); } catch (Exception e) { e.printStackTrace(); }finally { //3. Shut off try { if (fr!=null) { fr.close(); } if (fw!=null) { fw.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4. Character buffer stream
- Advantages: high efficiency; It can be read line by line, and can wrap when writing; The content can be added; The code can be set
- Disadvantages: creating flow is troublesome
eg:public static void main(String[] args) throws IOException { //Declare stream object BufferedReader br=null; BufferedWriter bw=null; try { //1. Create flow object br=new BufferedReader(new InputStreamReader(new FileInputStream("D:"+File.separator+ "Once upon a time, there was a Lingjian mountain.txt"), "utf-8")); bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("c1.txt"), "utf-8")); //2. Read and write while streaming, read line by line and write line by line String content; while ((content=br.readLine())!=null) { //Write a row every time you read a row bw.write(content); //Line feed bw.newLine(); //Refresh bw.flush(); } System.out.println("Success copy "); } catch (Exception e) { e.printStackTrace(); }finally { //3. Shut off if (br!=null) { br.close(); } if (bw!=null) { bw.close(); } } }
Summary:
1. Print stream printstream (byte print stream, processing stream), printwriter (character print stream, processing stream)
1.1: use of byte print stream, in-depth understanding of system out. println()/print()/printf()/append()/write()
eg:public static void main(String[] args) { //Declare stream object PrintStream ps1=null; try { //1. Create flow object ps1=new PrintStream("d1.txt"); //2. Write the contents in the file with the flow direction ps1.append("I love Qianfeng"); ps1.printf("%.2f", 3.123234344343); ps1.println("I love Beijing"); ps1.print("I love China"); ps1.write("ha-ha".getBytes()); //Note: system Out is PrintStream System.out.println("Write successful"); System.out.append("1111"); System.out.write("dfefe".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally { //3. Shut off if (ps1!=null) { ps1.close(); } } }
1.2: (Extended) output redirection: redefine a direction of output for the stream Transfer the content originally output in the console to a file
eg: public static void main(String[] args) throws FileNotFoundException { //Output redirection System.setOut(new PrintStream("f1.txt")); //Output the content originally output to the console, change the direction of the flow, and output it to a file System.out.println("Remain true to our original aspiration"); System.out.println("Fang de always"); }
1.3: (extension) input redirection: redefine a direction for the stream to receive data The data entered by the keyboard will be received on the console, and now the data will be received in the file
eg:public static void main(String[] args) throws FileNotFoundException { //input redirection System.setIn(new FileInputStream("f1.txt")); Scanner input=new Scanner(System.in); System.out.println("receive data :"); String s1=input.next(); String s2=input.next(); System.out.println("The data received is:"+s1); System.out.println("The data received is:"+s2); }
2. Object flow:
2.1: serialization: the process of storing objects in Java programs (memory) in files on disk
- Persistence: store the data stored temporarily in memory on disk for a long time
- Deserialization: the process of reading objects from files on disk into Java programs (memory)
2.2: object output stream: ObjectOutputStream
- The process of using object output to write objects to the file is the serialization process
- Note: the contents of the file written by the object stream cannot be viewed directly (encrypted), but should be read by the deserialized object
eg:public static void main(String[] args) throws IOException { //Declare stream object ObjectOutputStream oos=null; try { //1. Create flow object oos=new ObjectOutputStream(new FileOutputStream("h1.txt")); //2. The first method: write a String object to the file by using the object stream call method //Prepare a string object // String s1 = "I love China"; // oos.writeObject(s1); //The second method: write a user-defined object to the file by calling the method of object flow // Student stu1=new Student("Zhang San, 18, 'male'); // oos.writeObject(stu1); //The third method: store multiple objects in the object stream: store multiple objects in the collection, and then serialize the collection as a whole Student stu1=new Student("Zhang san1", 18,'male'); Student stu2=new Student("Zhang San 2", 28,'male'); Student stu3=new Student("Zhang SAN3", 38,'male'); List<Student> stulist=new ArrayList(); stulist.add(stu1); stulist.add(stu2); stulist.add(stu3); //Serialize the collection as a whole oos.writeObject(stulist); System.out.println("Write successful"); } catch (Exception e) { e.printStackTrace(); }finally { //3. Shut off if (oos!=null) { oos.close(); } } }
2.3: object input stream:
- The process of reading the object in the file with the object input stream is the deserialization process
eg:public static void main(String[] args) throws IOException { //Declare stream object ObjectInputStream oos=null; try { //1. Create flow object oos=new ObjectInputStream(new FileInputStream("h1.txt")); //2. The first method: use the object stream call method to read the String object in the file // String s1=(String) oos.readObject(); // System.out.println("read content:" + s1); //The second method: use the object stream call method to read the file and write a custom object // Student stu1=(Student) oos.readObject(); // System.out.println("read content:" + stu1); //The third method: store multiple objects into the collection, then serialize the collection as a whole, and read the collection with the object stream List<Student> stulist=(List<Student>) oos.readObject(); for (Student s : stulist) { System.out.println(s); } System.out.println("Read complete"); } catch (Exception e) { e.printStackTrace(); }finally { //3. Shut off if (oos!=null) { oos.close(); } } }
2.4: pay attention to when reading and writing object streams
- The method of writing object to the file should match the method of reading object, otherwise EOFException exception will be reported
- The write data type () should be consistent with the read data type ()
2.5: only supports (implements) Java io. Only objects of serializable interface can be written to the object stream
2.6: Problems
- The object output stream is used to store the object in a custom class into the file on disk, and there is no problem reading it with the object input stream. If the custom class is changed, the reading with the object input stream will report stream classdesc serialVersionUID = 7084766393580739456, and local class serialVersionUID = 3665876382104105971
- Reason: if the custom class only implements the serialization interface and has no fixed serialization version number, a different serialization version number will be automatically generated every time the custom class is changed Therefore, it will cause you to serialize the object of a user-defined class with one version number, and then read the object with a user-defined class with another version number, which will cause the version number exception
- Solution: fix the serialization version number while implementing the serialization interface for each class to be serialized
2.7: if a property in the serialization class does not want to be serialized, you can set the property to static or transient
2.8: serialize multiple objects with object stream, store multiple objects into the collection, and then serialize the collection as a whole Deserialization only needs to read a collection
3.Properties class: the configuration file can be read dynamically
eg:public static void main(String[] args) throws FileNotFoundException, IOException { //Create Properties object Properties p1=new Properties(); //Dynamically loading configuration files by calling methods with Properties objects p1.load(new FileInputStream("jdbc.properties")); //Get value through key with Properties object System.out.println("user name:"+p1.getProperty("username")); System.out.println("password:"+p1.getProperty("password")); System.out.println("drivername:"+p1.getProperty("drivername")); }
4. (Extended) decorator mode:
- Function: encapsulate the original class to make it more powerful
- To realize decorator mode, pay attention to the following points:
a. The decorator class should implement the same interface as the real class or inherit the same parent class
b. There is a reference to a real object in the decorator class (which can be passed in through the constructor of the decorator class)
c. The decoration class object accepts the request in the main class and sends the request to the real object (equivalent to passing the reference to the real object of the decoration class)
d. The decorator can add some additional functions after passing in the real object (because the decorating object and the real object have the same methods, the decorating object can add a certain operation to call the method of the real object, or call the method of the real object first, and then add its own method)