11-IO (core class library)

Thank you for passing by. I hope the student's notes can give you a trivial reference (2 / 100)
Java basic mind map, Links to the complete Java architecture

1, File class

1.1 what is the File class?

   java.io.File class is an abstract representation of file and directory pathnames. It is mainly used for the creation, search and deletion of files and directories.

1.2 variables and types of file class

code:

package com.wyh.File;
import java.io.File;

/*  File Variables and types of classes
    java.io.File class
    Abstract representation of file and directory pathnames.
    java Encapsulate the files and folders (directories) in the computer into a File class. We can use the File class to operate the files and folders
    We can use the method of the File class
        Create a file / folder
        Delete file / folder
        Get files / folders
        Determine whether the file / folder exists
        Traverse folders
        Gets the size of the file
    File Class is a system independent class. Any operating system can use the methods in this class

    Key: remember these three words
        file:file
        directory:Folder / directory
        path:route
 */
public class Demo01_File {
    public static void main(String[] args) {
        /*
            static String pathSeparator System related path separator, which is represented as a string for convenience.
            static char pathSeparatorChar The path separator associated with the system.

            static String separator The default name separator associated with the system, which is represented as a string for convenience.
            static char separatorChar Default name separator associated with the system.

            Operation path: the path cannot be written dead
            C:\develop\a\a.txt  windows
            C:/develop/a/a.txt  linux
            "C:"+File.separator+"develop"+File.separator+"a"+File.separator+"a.txt"
         */
        String pathSeparator = File.pathSeparator;
        System.out.println(pathSeparator);//Path separator: semicolon; linux: colon:

        String separator = File.separator;
        System.out.println(separator);// File name separator windows: backslash \ linux: forward slash/
    }
}

1.3 absolute path and relative path

Absolute path: the path starting from the drive letter. This is a complete path.
Relative path: relative to the path of the project directory, this is a convenient path, which is often used in development.
Example: insert xmind file. If it is in the same directory as the previously inserted file, it is the relative directory. If you go to a new folder, it is the absolute path.
code:

package com.wyh.File;
import java.io.File;
/*
    route:
        Absolute path: is a complete path
            Path starting with drive letter (c:,D:)
                c:\\a.txt
                C:\\Users\itcast\\IdeaProjects\\shungyuan\\123.txt
                D:\\demo\\b.txt
        Relative path: is a simplified path
            Relative refers to the root directory relative to the current project (C:\Users\itcast\IdeaProjects\shungyuan)
            If you use the root directory of the current project, the path can simplify writing
            C:\\Users\itcast\\IdeaProjects\\shungyuan\\123.txt-->Simplified as: 123 Txt (you can omit the root directory of the project)
        be careful:
            1.The path is case insensitive
            2.The file name separator in the path windows uses a backslash, which is an escape character, and two backslashes represent an ordinary backslash
 */
public class Demo02_File {
    public static void main(String[] args) {
        show01();
    }

    /*
        File(File parent, String child) Create a new File instance based on the parent abstract pathname and the child pathname string.
        Parameter: divides the path into two parts
            File parent:Parent path
            String child:Sub path
        Benefits:
             Parent path and child path can be written separately, which is very flexible to use; Both parent and child paths can be changed
             The parent path is of File type. You can use the File method to perform some operations on the path, and then use the path to create an object
     */
    private static void show03() {
        File parent = new File("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO");
        File file = new File(parent,"hello.java");
        System.out.println(file);//c:\hello.java
    }

    private static void show02(String parent, String child) {
        File file = new File(parent,child);
        System.out.println(file);//c:\a.txt
    }

    /*
     *route
     */
    private static void show01() {
        File f1 = new File("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\a.txt");
        System.out.println("f1 Path of"+f1.getAbsolutePath());// Absolute path

        File f2 = new File("a.txt");
        System.out.println("f2 Path of"+f2.getAbsolutePath());// Relative path

    }
}

1.4 what are the construction methods of file class?

public File(String pathname): create a new File instance by converting the given pathname string to an abstract pathname.
public File(String parent, String child): creates a new File instance from the parent pathname string and the child pathname string.
public File(File parent, String child): creates a new File instance from the parent abstract pathname and child pathname strings.
Tips:
      1. A File object represents a File or directory that actually exists in the hard disk
      2. Whether a File or directory exists in this path does not affect the creation of the File object

1.5 what are the common methods of file class?

Method of obtaining function
public String getAbsolutePath(): returns the absolute pathname string of this File.
public String getPath(): converts this File to a pathname string.
public String getName(): returns the name of the File or directory represented by this File.
public long length(): returns the length of the File represented by this File.
Description in API: length() indicates the length of the File. However, if the File object represents a directory, the return value is not specified
code:

package com.wyh.File;
import java.io.File;

/*
    File Class to get functions
        - public String getAbsolutePath() : Returns the absolute pathname string for this File.
        - public String getPath() : Convert this File to a pathname string.
        - public String getName()  : Returns the name of the File or directory represented by this File.
        - public long length()  : Returns the length of the File represented by this File.
 */
public class Demo03_File {
    public static void main(String[] args) {
        show03();
    }

    /*
        public long length()  : Returns the length of the File represented by this File.
        Gets the size of the file specified by the constructor, in bytes
        be careful:
            There is no concept of folder size. You can't get the size of the folder
            If the path given in the constructor does not exist, the length method returns 0
     */
    private static void show04() {
        File f1 = new File("C:\\develop\\a\\1.jpg");
        long l1 = f1.length();
        System.out.println(l1);//780831 bytes

        File f2 = new File("C:\\develop\\a\\2.jpg");
        System.out.println(f2.length());//0

        File f3 = new File("C:\\develop\\a");
        System.out.println(f3.length());//0 folder has no concept of size
    }

    /*
        public String getName()  : Returns the name of the File or directory represented by this File.
        What you get is the end of the constructor pass path (file / folder)
     */
    private static void show03() {
        File f1 = new File("C:\\Users\\itcast\\IdeaProjects\\shungyuan\\a.txt");
        String name1 = f1.getName();
        System.out.println(name1);//a.txt

        File f2 = new File("E:\\BaiduNetdiskDownload");
        String name2 = f2.getName();
        System.out.println(name2);//shungyuan
    }

    /*
        public String getPath() : Convert this File to a pathname string.
        Gets the path passed in the constructor

        toString Method calls the getPath method
        Source code:
            public String toString() {
                return getPath();
            }
     */
    private static void show02() {
        File f1 = new File("C:\\Users\\itcast\\IdeaProjects\\shungyuan\\a.txt");
        File f2 = new File("a.txt");
        String path1 = f1.getPath();
        System.out.println(path1);//C:\Users\itcast\IdeaProjects\shungyuan\a.txt
        String path2 = f2.getPath();
        System.out.println(path2);//a.txt

        System.out.println(f1);//C:\Users\itcast\IdeaProjects\shungyuan\a.txt
        System.out.println(f1.toString());//C:\Users\itcast\IdeaProjects\shungyuan\a.txt
    }

    /*
        public String getAbsolutePath() : Returns the absolute pathname string for this File.
        Gets the path passed in the constructor
        Whether the path is absolute or relative, the getAbsolutePath method returns an absolute path
     */
    private static void show01() {
        File f1 = new File("C:\\Users\\itcast\\IdeaProjects\\shungyuan\\a.txt");
        String absolutePath1 = f1.getAbsolutePath();
        System.out.println(absolutePath1);//C:\Users\itcast\IdeaProjects\shungyuan\a.txt

        File f2 = new File("a.txt");
        String absolutePath2 = f2.getAbsolutePath();
        System.out.println(absolutePath2);//C:\Users\itcast\IdeaProjects\shungyuan\a.txt
    }
}

Method of judging function
public boolean exists(): whether the File or directory represented by this File actually exists.
public boolean isDirectory(): whether this File indicates a directory.
public boolean isFile(): this File indicates whether it is a File.
code:

package com.wyh.File;
import java.io.File;

/*
    File Method of class judgment function
        - public boolean exists() : Whether the File or directory represented by this File actually exists.
        - public boolean isDirectory() : This File indicates whether it is a directory.
        - public boolean isFile() : This File indicates whether it is a File.
 */
public class Demo04_File {
    public static void main(String[] args) {
        show02();
    }

    /*
        public boolean isDirectory() : This File indicates whether it is a directory.
            Used to determine whether the given path in the construction method ends in a folder
                Yes: true
                No: false
        public boolean isFile() : This File indicates whether it is a File.
            Used to determine whether the given path in the construction method ends in a file
                Yes: true
                No: false
        be careful:
            There are only files / folders in the hard disk of the computer. The two methods are mutually exclusive
            These two methods use the premise that the path must exist, otherwise both return false
     */
    private static void show02() {
        File f1 = new File("D:\\KwDownload\\08_FileAndRecursion\\aaa\\z.txt");

        //If it does not exist, there is no need to obtain it
        if(f1.exists()){
            System.out.println(f1.isDirectory());
            System.out.println(f1.isFile());
        }

        File f2 = new File("D:\\KwDownload\\08_FileAndRecursion\\111\\222\\333\\444");
        if(f2.exists()){
            System.out.println(f2.isDirectory());//true
            System.out.println(f2.isFile());//false
        }

        File f3 = new File("C:\\Users\\itcast\\IdeaProjects\\shungyuan\\shungyuan.iml");
        if(f3.exists()){
            System.out.println(f3.isDirectory());//false
            System.out.println(f3.isFile());//true
        }

    }

    /*
        public boolean exists() : Whether the File or directory represented by this File actually exists.
        Used to determine whether the path in the construction method exists
            Presence: true
            Does not exist: false
     */
    private static void show01() {
        File f1 = new File("C:\\Users\\itcast\\IdeaProjects\\shungyuan");
        System.out.println(f1.exists());//true

        File f2 = new File("C:\\Users\\itcast\\IdeaProjects\\shung");
        System.out.println(f2.exists());//false

        File f3 = new File("shungyuan.iml");//Relative path C: \ users \ itcast \ ideaprojects \ shungyuan \ shungyuan iml
        System.out.println(f3.exists());//true

        File f4 = new File("a.txt");
        System.out.println(f4.exists());//false
    }
}

Method for creating and deleting functions
public boolean createNewFile(): creates a new empty file if and only if the file with this name does not exist yet.
public boolean delete(): deletes the File or directory represented by this File.
public boolean mkdir(): create the directory represented by this File.
public boolean mkdirs(): create the directory represented by this File, including any required but nonexistent parent directory.
Description in API:
code:

package com.wyh.File;
import java.io.File;
import java.io.IOException;

/*
    File Class to create and delete functions
        - public boolean createNewFile() : Create a new empty file if and only if the file with that name does not already exist.
        - public boolean delete() : Delete the File or directory represented by this File.
        - public boolean mkdir() : Create the directory represented by this File.
        - public boolean mkdirs() : Create the directory represented by this File, including any required but nonexistent parent directory.
 */
public class Demo05_File {
    public static void main(String[] args) throws IOException {
      show03();
    }
    /*
           public boolean delete() : Delete the File or directory represented by this File.
           With this method, you can delete the file / folder given in the construction method path
           Return value: Boolean
               true:The file / folder is deleted successfully and returns true
               false:If there is content in the folder, it will not be deleted and false will be returned; The path in the construction method does not exist false
           be careful:
               delete The method is to delete files / folders directly on the hard disk without going to the recycle bin. Be careful when deleting
        */
    private static void show03() {
        File f1 = new File("08_FileAndRecursion\\New folder");
        boolean b1 = f1.delete();
        System.out.println("b1:"+b1);

        File f2 = new File("08_FileAndRecursion\\abc.txt");
        System.out.println(f2.delete());
    }

    /*
      public boolean mkdir() : Create a single level empty folder
      public boolean mkdirs() : You can create either a single level empty folder or a multi-level folder
      The path and name of the created folder are given in the construction method (parameters of the construction method)
       Return value: Boolean
           true:The folder does not exist. Create a folder and return true
           false:If the folder exists, it will not be created, and false will be returned; The path given in the constructor does not exist and returns false
       be careful:
           1.This method can only create folders, not files
    */
    private static void show02() {
        File f1 = new File("08_FileAndRecursion\\aaa");
        boolean b1 = f1.mkdir();
        System.out.println("b1:"+b1);

        File f2 = new File("08_FileAndRecursion\\111\\222\\333\\444");
        boolean b2 = f2.mkdirs();
        System.out.println("b2:"+b2);

        File f3 = new File("08_FileAndRecursion\\abc.txt");
        boolean b3 = f3.mkdirs();//Look at the type. It's a file
        System.out.println("b3:"+b3);

        File f4 = new File("08_F\\ccc");
        boolean b4 = f4.mkdirs();//No exceptions will be thrown, the path does not exist, and will not be created
        System.out.println("b4:"+b4);
    }
    /*
           public boolean createNewFile() : Create a new empty file if and only if the file with that name does not already exist.
           The path and name of the created file are given in the construction method (parameters of the construction method)
           Return value: Boolean
               true:The file does not exist. Create the file and return true
               false:The file exists and will not be created. false is returned
           be careful:
               1.This method can only create files, not folders
               2.The path to create the file must exist, otherwise an exception will be thrown

           public boolean createNewFile() throws IOException
           createNewFile The declaration throws an IOException. When we call this method, we must handle the exception, either throws or trycatch
        */
    private static void show01() throws IOException {
        File f1 = new File("D:\\KwDownload\\08_FileAndRecursion\\1.txt");
        boolean b1 = f1.createNewFile();
        System.out.println("b1:"+b1);

        File f2 = new File("D:\\KwDownload\\08_FileAndRecursion\\2.txt");
        System.out.println(f2.createNewFile());

        File f3 = new File("D:\\KwDownload\\08_FileAndRecursion\\New folder");
        System.out.println(f3.createNewFile());//Don't be confused by the name, it depends on the type

       /* File f4 = new File("08_FileAndRecursi\\3.txt");
        System.out.println(f4.createNewFile());//Path does not exist, throw IOException*/
    }
}

1.6 directory traversal

public String[] list(): returns a String array representing all sub files or directories in the File directory.
public File[] listFiles(): returns a File array representing all sub files or directories in the File directory.
Tip: the File object calling the listFiles method must represent the actual directory, otherwise it returns null and cannot be traversed.
code:

package com.wyh.File;

import java.io.File;
import java.io.IOException;
import java.sql.SQLOutput;

/**
 * @Deacription File File traversal
 * @Author Wang Yuhui
 * @Date 2021/9/3 20:39
 * @Version 1.0
 **/
public class Task01 {
    // Java.io.*
    public static void main(String[] args) throws IOException {
        File e = new File("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO");
        File[] files =e.listFiles();
        ListFiles(files);
    }

    private static void ListFiles(File[] files) {
        if (files!= null && files.length>0){
            for (File file:files) {
                if (file.isFile()){
                    // file
                    if (file.getName().endsWith(".txt")){
                        file.delete();
                        System.out.println(file.getAbsolutePath()+"Deleted");
                    }
                }else{
                    // folder
                    File[] files1 = file.listFiles();
                    ListFiles(files1);
                }
            }
        }
    }
}

2, File filter

Illustration:
code:

package com.wyh.File;
import java.io.File;
import java.io.FileFilter;
/*
    Create the implementation class of FileFilter, override the filter method accept, and define the filter rules
 */
public class FileFilterImpl implements FileFilter{
    @Override
    public boolean accept(File pathname) {
        /*
            Filtering rules:
            In the accept method, judge whether the File object is java end
            If yes, return true
            If not, return false
         */
        //If pathname is a folder, return true and continue to traverse the folder
        if(pathname.isDirectory()){
            return true;
        }
        return pathname.getName().toLowerCase().endsWith(".java");
    }
}
package com.wyh.File;

import java.io.File;

/**
 * @Deacription File filter
 * @Author Wang Yuhui
 * @Date 2021/9/3 21:13
 * @Version 1.0
 **/
public class Demo06_FileFilter {
    public static void main(String[] args) {
        File file = new File("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO");
        getAllFile(file);
    }

    /*
        Define a method parameter to pass the directory of File type
        Method to traverse the directory
     */
    public static void getAllFile(File dir){
        File[] files = dir.listFiles(new FileFilterImpl());//Pass filter object
        for (File f : files) {
            //Judge whether the File object f obtained through traversal is a folder
            if(f.isDirectory()){
                //If f is a folder, continue to traverse the folder
                //We found that the getAllFile method is the method of passing folders and traversing folders
                //So just call the getAllFile method directly: recursion (call yourself)
                getAllFile(f);
            }else{
                //f is a Java file, which can be printed directly
                System.out.println(f);
            }
        }
    }
}
package com.wyh.File;
import java.io.File;

/*
    Requirements:
        Traverse the c:\abc folder and subfolders of the abc folder
        Just java terminated file
        c:\\abc
        c:\\abc\\abc.txt
        c:\\abc\\abc.java
        c:\\abc\\a
        c:\\abc\\a\\a.jpg
        c:\\abc\\a\\a.java
        c:\\abc\\b
        c:\\abc\\b\\b.java
        c:\\abc\\b\\b.txt
    We can use filters to achieve this
    In the File class, there are two methods overloaded with ListFiles. The parameters of the method pass the filter
    File[] listFiles(FileFilter filter)
    java.io.FileFilter Interface: filter for abstract pathnames (File objects).
        Function: used to filter files (File objects)
        Abstract method: a method used to filter files
            boolean accept(File pathname) Tests whether the specified abstract pathname should be included in a list of pathnames.
            Parameters:
                File pathname:Use the ListFiles method to traverse the directory and get each file object
    File[] listFiles(FilenameFilter filter)
    java.io.FilenameFilter Interface: class instances that implement this interface can be used to filter file names.
        Function: used to filter file names
        Abstract method: a method used to filter files
            boolean accept(File dir, String name) Tests whether the specified file should be included in a file list.
            Parameters:
                File dir:The traversed directory passed in the constructor
                String name:Use the ListFiles method to traverse the directory and get the name of each file / folder
    be careful:
        There is no implementation class for the two filter interfaces. We need to write our own implementation class, rewrite the filter method accept, and define our own filter rules in the method
 */
public class Demo07_FileFilter {
    public static void main(String[] args) {
        File file = new File("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO");
        getAllFile(file);
    }

    /*
        Define a method parameter to pass the directory of File type
        Method to traverse the directory
     */
    public static void getAllFile(File dir){
        //Pass filter objects using anonymous inner classes
        /*File[] files = dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                //Filter rule, pathname is folder or The file ending in java returns true
                return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java");
            }
        });*/

        //Optimize anonymous inner classes with Lambda expressions (there is only one abstract method in the interface)
        /*File[] files = dir.listFiles((File pathname)->{
            return pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java");
        });*/

        File[] files = dir.listFiles(pathname->pathname.isDirectory() || pathname.getName().toLowerCase().endsWith(".java"));

        /*File[] files = dir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                //Filter rule, pathname is folder or The file ending in java returns true
                return new File(dir,name).isDirectory() || name.toLowerCase().endsWith(".java");
            }
        });*/

        //Optimize anonymous inner classes with Lambda expressions (there is only one abstract method in the interface)
        /*File[] files = dir.listFiles((File d, String name)->{
            //Filter rule, pathname is folder or The file ending in java returns true
            return new File(d,name).isDirectory() || name.toLowerCase().endsWith(".java");
        });*/

        //File[] files = dir.listFiles((d,name)->new File(d,name).isDirectory() || name.toLowerCase().endsWith(".java"));

        for (File f : files) {
            //Judge whether the File object f obtained through traversal is a folder
            if(f.isDirectory()){
                //If f is a folder, continue to traverse the folder
                //We found that the getAllFile method is the method of passing folders and traversing folders
                //So just call the getAllFile method directly: recursion (call yourself)
                getAllFile(f);
            }else{
                //f is a file, which can be printed directly
                System.out.println(f);
            }
        }
    }
}

3, IO overview

3.1 what is IO?

We can regard this data transmission as a kind of data flow. According to the flow direction and based on memory, it is divided into input input and output, that is, the flow to memory is the input flow and the output flow out of memory.
I/O operation in Java mainly refers to the use of Java Input and output the contents under the IO package. Input is also called read data, and output is also called write data

3.2 classification of IO

According to the flow direction of data
Input stream: a stream that reads data from other devices into memory
Output stream: a stream that writes data out of memory to other devices
Type of pattern data
Byte stream: a stream that reads and writes data in bytes
Character stream: a stream that reads and writes data in character units

3.3 flow direction illustration of IO

3.4 top level parent classes

Byte stream
Byte input stream InputStream
Byte output stream OutputStream
Character stream
Character input stream Reader
Character output stream Writer

4, Byte stream

4.1 is everything a byte?

It is stored in binary numbers, one byte at a time, so it is the same when transmitting. Therefore, byte stream can transfer any file data. When operating a stream, we should always make it clear that no matter what kind of stream object is used, the underlying transmission is always binary data.

4.2 byte output stream [OutputStream]

Introduction: Java io. OutputStream abstract class is a superclass representing all classes of byte output stream, which writes the specified byte information to the destination.
Basic common function method
public void close(): close this output stream and release all system resources associated with this stream.
public void flush(): flushes this 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 them to this output stream starting from offset off
public abstract void write(int b): writes the specified bytes to this output stream
Tips:
close method, which must be called to release system resources when the operation of the stream is completed

4.3 fileoutputstream class

Introduction: Java io. The fileoutputstream class is a file output stream used to write data out to a file
Construction method:
public FileOutputStream(File file): creates a File output stream to write to the File represented by the specified File object.
public FileOutputStream(String name): creates a file output stream to write to a file with the specified name
Write byte data
      1. Write Bytes: the write(int b) method can write one byte of data at a time
Tips:
      1. Although the parameter is four bytes of int type, only one byte of information will be reserved.
      2. After the stream operation is completed, you must release system resources and call the close method. Remember.
      2. Write out byte array: write(byte[] b). You can write out the data in the array each time
      3. Write out the byte array of the specified length: write(byte[] b, int off, int len). Each write starts from the off index, len bytes
Data append and continue
Purpose: keep the data in the target file and continue to add new data
Method
Public fileoutputstream (File, Boolean append): creates a File output stream to write to the File represented by the specified File object.
public FileOutputStream(String name, boolean append): creates a file output stream to write to a file with a specified name.
code:

package com.wyh.Io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Deacription Byte output stream - FileOutputStream class
 * @Author Wang Yuhui
 * @Date 2021/9/4 8:21
 * @Version 1.0
 **/
public class Demo08_OutputStream {

    public static void main(String[] args) throws IOException {
        demo03();
    }

    /**
     * Basic use of byte output stream
     * @throws IOException
     */
    public static void demo01() throws IOException {
        //1. Create a FileOutputStream object to transfer the destination of written data in the construction method
        FileOutputStream fos = new FileOutputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\b.txt");
        //2. Call the write method in the FileOutputStream object to write the data to the file
        //public abstract void write(int b): outputs the specified bytes to the stream.
        fos.write(97);
        //3. Release resources (stream use will occupy a certain amount of memory, and the memory should be emptied after use to improve the efficiency of the provider)
        fos.close();
    }

    /*
    How to write multiple bytes at a time:
        - public void write(byte[] b): Writes b.length bytes to this output stream from the specified byte array.
        - public void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array and outputs to this output stream starting from offset off.
    */
    public static void demo02() throws IOException{
        //Create a FileOutputStream object and bind the destination of data to be written in the construction method
        FileOutputStream fos = new FileOutputStream(new File("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\c.txt"));
        //Call the write method in the FileOutputStream object to write the data to the file
        //Display 100 in the file and write a byte
        fos.write(49);
        fos.write(48);
        fos.write(48);

        /*
            public void write(byte[] b): Writes b.length bytes to this output stream from the specified byte array.
            Write multiple bytes at a time:
                If the first byte written is a positive number (0-127), the ASCII table will be queried during display
                If the first byte written is negative, the first byte and the second byte will form a Chinese display. Query the system default code table (GBK)
         */
        byte[] bytes = {65,66,67,68,69};//ABCDE
        fos.write(bytes);

         /*
            public void write(byte[] b, int off, int len) : Writes a portion of the byte array to a file
                int off:Start index of array
                int len:Write a few bytes
         */
        fos.write(bytes,1,2);//BC

         /*
            Write character method: you can use the method in the String class to convert a String into a byte array
                byte[] getBytes()  Convert string to byte array
         */
        byte[] bytes2 = "Hello".getBytes();
        System.out.println(Arrays.toString(bytes2));//[-28, -67, -96, -27, -91, -67]
        fos.write(bytes2);

        //Release resources
        fos.close();
    }

    /*
        Append / continue: a construction method using two parameters
            FileOutputStream(String name, boolean append)Creates an output file stream that writes data to a file with the specified name.
            FileOutputStream(File file, boolean append) Creates a File output stream that writes data to the File represented by the specified File object.
            Parameters:
               String name,File file:Destination to write data
               boolean append:Append write switch
                true:Creating an object will not overwrite the source file. Continue to append write data at the end of the file
                false:Create a new file and overwrite the source file
        Write line breaks: write line breaks
            windows:\r\n
            linux:/n
            mac:/r
     */
    public static void demo03() throws IOException{
        FileOutputStream fos = new FileOutputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\c.txt",true);
        for (int i = 1; i <=10 ; i++) {
            fos.write("Hello".getBytes());
            fos.write("\r\n".getBytes());
        }
        fos.close();
    }

}

4.4 byte input stream [InputStream]

Introduction: Java io. InputStream abstract class is a super class representing all classes of byte input stream, which can read byte information into memory. It defines the basic common function method of byte input stream.
Basic common function method
public void close(): close this input stream and release any system resources associated with this stream
public abstract int read(): reads the next byte of data from the input stream
public int read(byte[] b): read some bytes from the input stream and store them in byte array B
Tip: close method. This method must be called when the stream operation is completed to release system resources

4.5 FileInputStream class

Introduction: Java io. The FileInputStream class is a file input stream that reads bytes from a file
Construction method
FileInputStream(File file): create a FileInputStream by opening a connection to the actual file, which is named by the file object file in the file system
FileInputStream(String name): create a FileInputStream by opening a connection to the actual file, which is named by the pathname in the file system
Read byte data
      1. Read bytes: the read method can read one byte of data at a time, promote it to int type, read it to the end of the file, and return - 1
      2. Read using byte array: read(byte[] b). Each time the length of B is read into the array, return the number of valid bytes read. When reading to the end, return - 1
Tips:
Using array to read multiple bytes at a time reduces the number of IO operations between systems, thus improving the efficiency of reading and writing. It is suggested that when using byte stream to read text in development, there may be garbled code and separate problems of reading half a word. At this time, it is necessary to use character stream.
code:

package com.wyh.Io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Deacription Byte input stream - FileInputStream class
 * @Author Wang Yuhui
 * @Date 2021/9/4 8:32
 * @Version 1.0
 **/
public class Demo09_InputStream {


    public static void main(String[] args) throws IOException {
        demo02();
    }

    /**
     * Basic usage of byte input stream
     *  Principle of reading data (hard disk -- > memory)
     *         java Program -- > JVM -- > OS -- > OS method of reading data -- > read file
     *  Usage steps of byte input stream (key points):
     *         1.Create a FileInputStream object and bind the data source to be read in the construction method
     *         2.Use the read method in the FileInputStream object to read the file
     *         3.Release resources
     * @throws IOException
     */
    public static void demo01() throws IOException {
        //1. Create a FileInputStream object and bind the data source to be read in the construction method
        FileInputStream fis = new FileInputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\c.txt");
        //2. Use the read method in the FileInputStream object to read the file
        //int read() reads a byte in the file and returns, and returns - 1 at the end of the file
        /*int len = fis.read();
        System.out.println(len);//97 a

        len = fis.read();
        System.out.println(len);// 98 b

        len = fis.read();
        System.out.println(len);//99 c

        len = fis.read();
        System.out.println(len);//-1

        len = fis.read();
        System.out.println(len);//-1*/

        /*
            It is found that reading the file above is a repeated process, so loop optimization can be used
            If you don't know how many bytes there are in the file, use the while loop
            while The cycle end condition ends when - 1 is read

            Boolean expression (len = FIS. Read())=- one
                1.fis.read():Read a byte
                2.len = fis.read():Assign the read bytes to the variable len
                3.(len = fis.read())!=-1:Judge whether the variable len is not equal to - 1
         */
        int len = 0; //Record the bytes read
        while((len = fis.read())!=-1){
            System.out.println(len);//abc
        }
        //3. Release resources
        fis.close();
    }

    /*Byte input stream reads multiple bytes at a time:
            int read(byte[] b) A certain number of bytes are read from the input stream and stored in the buffer array b.
        Two things are clear:
            1.Function of the parameter byte [] of the method?
                It acts as a buffer and stores multiple bytes read each time
                The length of an array is defined as 1024(1kb) or an integer multiple of 1024
            2.What is the return value int of the method?
                Number of valid bytes read each time

        String Class construction method
            String(byte[] bytes) :Convert byte array to string
            String(byte[] bytes, int offset, int length) Convert part of byte array to string offset: start index of array length: number of bytes converted
     */
    public static void demo02() throws IOException{
        //Create a FileInputStream object and bind the data source to be read in the construction method
        FileInputStream fis = new FileInputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\c.txt");
        //Read the file using the read method in the FileInputStream object
        //int read(byte[] b) reads a certain number of bytes from the input stream and stores them in buffer array B.
        /*byte[] bytes = new byte[2];
        int len = fis.read(bytes);
        System.out.println(len);//2
        //System.out.println(Arrays.toString(bytes));//[65, 66]
        System.out.println(new String(bytes));//AB

        len = fis.read(bytes);
        System.out.println(len);//2
        System.out.println(new String(bytes));//CD

        len = fis.read(bytes);
        System.out.println(len);//1
        System.out.println(new String(bytes));//ED

        len = fis.read(bytes);
        System.out.println(len);//-1
        System.out.println(new String(bytes));//ED*/

        /*
            It is found that the above reading is a repeated process, and loop optimization can be used
            I don't know how many bytes there are in the file, so I use the while loop
            while The condition for the end of the cycle is read to the end of - 1
         */
        byte[] bytes = new byte[1024];//Store multiple bytes read
        int len = 0; //Record the number of valid bytes read each time
        while((len = fis.read(bytes))!=-1){
            //String(byte[] bytes, int offset, int length) converts a part of the byte array into a string offset: the start index of the array length: the number of bytes converted
            System.out.println(new String(bytes,0,len));
        }

        //Release resources
        fis.close();
    }
}

5, Character stream

5.1 byte stream problem?

There may be a small problem when using byte stream to read text files. When Chinese characters are encountered, complete characters may not be displayed because a Chinese character may occupy multiple bytes of storage. Therefore, Java provides some character stream classes to read and write data in character units, which are specially used to process text files.

5.2 character input stream [ Reader ]

Introduction: Java io. The reader abstract class is a superclass that represents all classes used to read character streams. It can read character information into memory.
Basic common function method
public void close(): close this flow and release any system resources associated with this flow
public int read(): reads 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

5.3 FileReader class

Introduction: Java io. The FileReader class is a convenient class for reading character files. The system default character encoding and default byte buffer are used during construction
Tips:
      1. Character encoding: the correspondence rule between bytes and characters. The Chinese code of Windows system is UTF-8 in GBK code table idea by default
      2. Byte buffer: a byte array used to temporarily store byte data
Construction method
FileReader (File): create a new FileReader and give the File object to be read
FileReader(String fileName): create a new FileReader and give the name of the file to be read
Read character data
      1. Read character: the read method can read data one character at a time, promote it to int type, read it to the end of the file, and return - 1
      2. Read using the character array: read(char[] cbuf). Each time the length of b is read into the array, return the number of valid characters read. When reading to the end, return - 1
code:

package com.wyh.Io;

import java.io.FileReader;
import java.io.IOException;

/*
    java.io.Reader:Character input stream is the top-level parent class of character input stream. It defines some common member methods and is an abstract class

    Common membership methods:
        int read() Read a single character and return.
        int read(char[] cbuf)Read multiple characters at a time and read the characters into the array.
        void close() Close the flow and release all resources associated with it.

    java.io.FileReader extends InputStreamReader extends Reader
    FileReader:File character input stream
    Function: read the data in the hard disk file into the memory in the form of characters

    Construction method:
        FileReader(String fileName)
        FileReader(File file)
        Parameter: read the data source of the file
            String fileName:Path to file
            File file:A file
        FileReader Function of construction method:
            1.Create a FileReader object
            2.The FileReader object will be pointed to the file to be read
    Steps for using character input stream:
        1.Create a FileReader object and bind the data source to be read in the constructor
        2.Use the read method in the FileReader object to read the file
        3.Release resources
 */
public class Demo10_Reader {
    public static void main(String[] args) throws IOException {
        //1. Create a FileReader object and bind the data source to be read in the construction method
        FileReader fr = new FileReader("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\c.txt");
        //2. Use the read method in the FileReader object to read the file
        //int read() reads a single character and returns.
        /*int len = 0;
        while((len = fr.read())!=-1){
            System.out.print((char)len);
        }*/

        //int read(char[] cbuf) reads multiple characters at a time and reads the characters into the array.
        char[] cs = new char[1024];//Store multiple characters read
        int len = 0;//Records the number of valid characters read each time
        while((len = fr.read(cs))!=-1){
            /*
                String Class construction method
                String(char[] value) Convert a character array to a string
                String(char[] value, int offset, int count) Convert a part of the character array to the number of count conversion of the start index of the string offset array
             */
            System.out.println(new String(cs,0,len));
        }
        //3. Release resources
        fr.close();
    }
}

5.4 character output stream [Writer]

Introduction: Java io. The writer abstract class is a superclass that represents all classes used to write out the character stream and writes the specified character information to the destination.
Basic common function method
void write(int c): write a single character
void write(char[] cbuf): write character array
abstract void write(char[] cbuf, int off, int len): write a part of the character array, the start index of the off array, and the number of characters written by Len
void write(String str): writes a string
void write(String str, int off, int len): write a part of the string, off the start index of the string, and Len the number of characters written
void flush(): flush the buffer of the stream
void close(): close this stream, but refresh it first

5.5FileWriter class

Description: close this stream, but refresh it first
Construction method:
FileWriter (File): create a new FileWriter and give the File object to be read
FileWriter(String fileName): create a new FileWriter and give the name of the file to be read
Basic write data
Write out characters: write(int b) method can write out character data one at a time
Tips:
      1. Although the parameter is four bytes of int type, only one character of information will be reserved
      2. The close method is not called, and the data is only saved to the buffer and not written out to the file
code:

package com.wyh.Io;
import java.io.FileWriter;
import java.io.IOException;

/*
    java.io.Writer:Character output stream is the top-level parent class of all character output streams. It is an abstract class

    Common membership methods:
        - void write(int c) Write a single character.
        - void write(char[] cbuf)Write character array.
        - abstract  void write(char[] cbuf, int off, int len)Write a part of the character array, the start index of the off array, and the number of characters written by len.
        - void write(String str)Write string.
        - void write(String str, int off, int len) Write a part of the string, off the start index of the string, and len the number of characters written.
        - void flush()Flush the buffer of the stream.
        - void close() Close this stream, but refresh it first.

    java.io.FileWriter extends OutputStreamWriter extends Writer
    FileWriter:File character output stream
    Function: write character data in memory to file

    Construction method:
        FileWriter(File file)Construct a FileWriter object based on the given File object.
        FileWriter(String fileName) Construct a FileWriter object according to the given file name.
        Parameter: destination to write data
            String fileName:Path to file
            File file:It's a file
        Function of construction method:
            1.A FileWriter object is created
            2.The file is created according to the path of the file / file passed in the construction method
            3.The FileWriter object will be pointed to the created file

    Steps for using character output stream (key points):
        1.Create a FileWriter object and bind the destination of data to be written in the constructor
        2.Use the method write in FileWriter to write data to the memory buffer (the process of converting characters into bytes)
        3.Use the flush method in FileWriter to flush the data in the memory buffer into the file
        4.Free resources (the data in the memory buffer will be flushed to the file first)
 */
public class Demo11_Writer {
    public static void main(String[] args) throws IOException {
        demo02();
    }


    /**
     * Basic use
     * @throws IOException
     */
    public static void demo01() throws IOException{
        //1. Create a FileWriter object and bind the destination of data to be written in the construction method
        FileWriter fw = new FileWriter("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\d.txt");
        //2. Use the method write in FileWriter to write data into the memory buffer (the process of converting characters into bytes)
        //void write(int c) writes a single character.
        fw.write(97);
        //3. Use the flush method in FileWriter to flush the data in the memory buffer into the file
        fw.flush();
        //4. Release resources (the data in the memory buffer will be flushed to the file first)
        fw.close();
    }


    /*
      Other methods of writing data in character output stream
            - void write(char[] cbuf)Write character array.
            - abstract  void write(char[] cbuf, int off, int len)Write a part of the character array, the start index of the off array, and the number of characters written by len.
            - void write(String str)Write string.
            - void write(String str, int off, int len) Write a part of the string, off the start index of the string, and len the number of characters written.
     */
    public static void demo02() throws IOException{
        FileWriter fw = new FileWriter("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\d.txt");
        char[] cs = {'a','b','c','d','e'};
        //void write(char[] cbuf) writes to the character array.
        fw.write(cs);//abcde

        //void write(char[] cbuf, int off, int len) writes a part of the character array, the start index of the off array, and the number of characters written by Len.
        fw.write(cs,1,3);//bcd

        //void write(String str) writes a string.
        fw.write("programmer");

        //void write(String str, int off, int len) writes a part of the string, the start index of the off string, and the number of characters written by Len.
        fw.write("Let's start, programmer",2,3);

        fw.close();
    }

    /*
        Continuation and line feed
        Append: a construction method that uses two parameters
            FileWriter(String fileName, boolean append)
            FileWriter(File file, boolean append)
            Parameters:
                String fileName,File file:Destination to write data
                boolean append:Renew switch true: new files will not be created to overwrite the source files, but can be renewed; false: create a new file to overwrite the source file
         Line breaks: line break symbols
            windows:\r\n
            linux:/n
            mac:/r
     */
    public static void demo03() throws IOException{
        FileWriter fw = new FileWriter("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\g.txt",true);
        for (int i = 0; i <10 ; i++) {
            fw.write("HelloWorld"+i+"\r\n");
        }
        fw.close();
    }
}

Close and refresh
Why?
Because of the built-in buffer, characters cannot be written out to the file without closing the output stream. However, closed stream objects cannot continue to write data. If we want to write data and continue to use the stream, we need the flush method.
Flush: flush the buffer, and the stream object can continue to be used
close: flush the buffer first, and then notify the system to release resources. Stream objects can no longer be used
Tips:
Even if the flush method writes out the data, the close method must be called at the end of the operation to release the system resources
code:

package com.wyh.Io;
import java.io.FileWriter;
import java.io.IOException;

/*
    flush Method and close method
        - flush : Flush the buffer and the stream object can continue to be used.
        - close:  Flush the buffer first, and then notify the system to release resources. Stream objects can no longer be used.
 */
public class Demo12_CloseAndFlush {
    public static void main(String[] args) throws IOException {
        //1. Create a FileWriter object and bind the destination of data to be written in the construction method
        FileWriter fw = new FileWriter("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\e.txt");
        //2. Use the method write in FileWriter to write data into the memory buffer (the process of converting characters into bytes)
        //void write(int c) writes a single character.
        fw.write(97);
        //3. Use the flush method in FileWriter to flush the data in the memory buffer into the file
        fw.flush();
        //After refreshing, the stream can continue to be used
        fw.write(98);

        //4. Release resources (the data in the memory buffer will be flushed to the file first)
        fw.close();
        //After the close method, the stream has been closed and has disappeared from memory. The stream can no longer be used
        fw.write(99);//IOException: Stream closed
    }
}

Write other data
      1. Write out the character array: write(char[] cbuf) and write(char[] cbuf, int off, int len). You can write out the data in the character array each time. The usage is similar to FileOutputStream
      2. Write out string: write(String str) and write(String str, int off, int len). You can write out the data in the string each time, which is more convenient
      3. Continue and line feed: the operation is similar to FileOutputStream
Tip: character stream can only operate text files, not pictures, videos and other non text files. When we simply read or write text files, we use character stream. In other cases, we use byte stream
Small exercise: document copying

package com.wyh.Io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Deacription File copying exercise: read and write
 *     Clear: (this location file is optional)
 *         Data source: C: \ \ 1 jpg
 *         Destination of data: D: \ \ 1 jpg
 *
 *     To copy a file:
 *         1.Create a byte input stream object and bind the data source to be read in the construction method
 *         2.Create a byte output stream object and bind the destination to be written in the construction method
 *         3.Read the file using the method read in the byte input stream object
 *         4.Use the write method in the byte output stream to write the read bytes to the destination file
 *         5.Release resources
 * @Author Wang Yuhui
 * @Date 2021/9/4 13:43
 * @Version 1.0
 **/
public class Task02 {
    public static void main(String[] args) throws IOException {
        long s = System.currentTimeMillis();
        //1. Create a byte input stream object and bind the data source to be read in the construction method
        FileInputStream fis = new FileInputStream("c:\\Wang Yuhui.jpg");
        //2. Create a byte output stream object and bind the destination to be written in the construction method
        FileOutputStream fos = new FileOutputStream("d:\\Wang Yuhui.jpg");

        //Read one byte at a time and write one byte at a time
        //3. Use the read method in the byte input stream object to read the file
        /*int len = 0;
        while((len = fis.read())!=-1){
            //4.Use the write method in the byte output stream to write the read bytes to the destination file
            fos.write(len);
        }*/

        //Use array buffer to read multiple bytes and write multiple bytes
        byte[] bytes = new byte[1024];
        //3. Use the read method in the byte input stream object to read the file
        int len = 0;//Number of valid bytes read each time
        while((len = fis.read(bytes))!=-1){
            //4. Use the write method in the byte output stream to write the read bytes to the destination file
            fos.write(bytes,0,len);
        }

        //5. Release resources (write is closed first, then read is closed; if it is finished, it must be finished reading)
        fos.close();
        fis.close();
        long e = System.currentTimeMillis();
        System.out.println("Total time taken to copy files:"+(e-s)+"millisecond");
    }
}

6, Conversion flow

6.1 what is character encoding?

According to certain rules, storing characters in the computer is called encoding. On the contrary, the binary number stored in the computer is parsed and displayed according to some rules, which is called decoding. Character Encoding: a set of correspondence rules between natural language characters and binary numbers

6.2 character set

What is Charset
Also called code table. It is a collection of all characters supported by the system, including national characters, punctuation marks, graphic symbols, numbers, etc
Character set diagram:

6.3InputStreamReader class

What is it?
Transform stream Java io. Inputstreamreader is a subclass of Reader and a bridge from byte stream to character stream. It reads bytes and decodes them into characters using the specified character set. Its character set can be specified by name or accept the default character set of the platform.
Construction method
InputStreamReader(InputStream in): creates a character stream that uses the default character set
InputStreamReader(InputStream in, String charsetName): creates a character stream with a specified character set
Construction example:
      InputStreamReader isr = new InputStreamReader(new FileInputStream("in.txt"));
      InputStreamReader isr2 = new InputStreamReader(new FileInputStream("in.txt") , "GBK");
code:

package com.wyh.ZhuanHuanLiu;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/*
    java.io.InputStreamReader extends Reader
    InputStreamReader:It is a bridge between byte flow and character flow: it uses the specified charset to read bytes and decode them into characters. (decoding: turn what you can't understand into what you can understand)

    Generic member methods inherited from parent class:
        int read() Read a single character and return.
        int read(char[] cbuf)Read multiple characters at a time and read the characters into the array.
        void close() Close the flow and release all resources associated with it.
    Construction method:
        InputStreamReader(InputStream in) Create an InputStreamReader that uses the default character set.
        InputStreamReader(InputStream in, String charsetName) Creates an InputStreamReader that uses the specified character set.
        Parameters:
            InputStream in:Byte input stream, used to read the bytes saved in the file
            String charsetName:The specified encoding table name is not case sensitive. It can be utf-8/UTF-8,gbk/GBK Do not specify default use UTF-8
     Use steps:
        1.Create an InputStreamReader object and pass the byte input stream and the specified encoding table name in the constructor
        2.Read the file using the read method in the InputStreamReader object
        3.Release resources
     matters needing attention:
        The code table name specified in the construction method must be the same as the file code, otherwise garbled code will occur
 */
public class Demo14_InputStreamReader {
    public static void main(String[] args) throws IOException {
        //read_utf_8();
        read_gbk();
    }

    /*
        Use InputStreamReader to read files in GBK format
     */
    private static void read_gbk() throws IOException {
        //1. Create InputStreamReader object and pass byte input stream and specified encoding table name in construction method
        //InputStreamReader isr = new InputStreamReader(new FileInputStream("10_IO\\gbk.txt"),"UTF-8");//???
        InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\gbk.txt"),"GBK");//Hello

        //2. Use the read method in the InputStreamReader object to read the file
        int len = 0;
        while((len = isr.read())!=-1){
            System.out.println((char)len);
        }
        //3. Release resources
        isr.close();
    }

    /*
        Use InputStreamReader to read files in UTF-8 format
     */
    private static void read_utf_8() throws IOException {
        //1. Create InputStreamReader object and pass byte input stream and specified encoding table name in construction method
        //InputStreamReader isr = new InputStreamReader(new FileInputStream("10_IO\\utf_8.txt"),"UTF-8");
        InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\utf_8.txt"));//Do not specify default use UTF-8
        //2. Use the read method in the InputStreamReader object to read the file
        int len = 0;
        while((len = isr.read())!=-1){
            System.out.println((char)len);
        }
        //3. Release resources
        isr.close();
    }
}

6.4OutputStreamWriter class

What is it?
Transform stream Java io. Outputstreamwriter is a subclass of Writer and a bridge from character stream to byte stream. Encodes characters into bytes using the specified character set. Its character set can be specified by name or accept the default character set of the platform.
Construction method
OutputStreamWriter(OutputStream in): creates a character stream that uses the default character set
OutputStreamWriter(OutputStream in, String charsetName): creates a character stream with a specified character set
Construction example
      OutputStreamWriter isr = new OutputStreamWriter(new FileOutputStream("out.txt"));
      OutputStreamWriter isr2 = new OutputStreamWriter(new FileOutputStream("out.txt") , "GBK");
code:

package com.wyh.ZhuanHuanLiu;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/*
    java.io.OutputStreamWriter extends Writer
    OutputStreamWriter: It is a bridge between character flow and byte stream: the characters to be written to the stream can be encoded into bytes using the specified charset. (Code: change what you can understand into what you can't understand)

    Continue common member methods from parent class:
        - void write(int c) Write a single character.
        - void write(char[] cbuf)Write character array.
        - abstract  void write(char[] cbuf, int off, int len)Write a part of the character array, the start index of the off array, and the number of characters written by len.
        - void write(String str)Write string.
        - void write(String str, int off, int len) Write a part of the string, off the start index of the string, and len the number of characters written.
        - void flush()Flush the buffer of the stream.
        - void close() Close this stream, but refresh it first.
    Construction method:
        OutputStreamWriter(OutputStream out)Create an OutputStreamWriter that uses the default character encoding.
        OutputStreamWriter(OutputStream out, String charsetName) Creates an OutputStreamWriter that uses the specified character set.
        Parameters:
            OutputStream out:Byte output stream, which can be used to write converted bytes to the file
            String charsetName:The specified encoding table name is not case sensitive. It can be utf-8/UTF-8,gbk/GBK Do not specify default use UTF-8
    Use steps:
        1.Create an OutputStreamWriter object and pass the byte output stream and the specified encoding table name in the construction method
        2.Use the write method in the OutputStreamWriter object to convert characters to bytes and store them in the buffer (encoding)
        3.Flush the bytes in the memory buffer into the file using the method flush in the OutputStreamWriter object (the process of writing bytes using a byte stream)
        4.Release resources
 */
public class Demo13_OutputStreamWriter {
    public static void main(String[] args) throws IOException {
        write_utf_8();
        //write_gbk();
    }

    /*
       Use the transform stream OutputStreamWriter to write files in GBK format
    */
    private static void write_gbk() throws IOException {
        //1. Create the OutputStreamWriter object and pass the byte output stream and the specified encoding table name in the construction method
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\gbk.txt"),"GBK");
        //2. Use the write method in the OutputStreamWriter object to convert characters into bytes and store them in the buffer (encoding)
        osw.write("Hello");
        //3. Use the method flush in the OutputStreamWriter object to flush the bytes in the memory buffer into the file (the process of writing bytes using byte stream)
        osw.flush();
        //4. Release resources
        osw.close();
    }

    /*
        Use the transform stream OutputStreamWriter to write files in UTF-8 format
     */
    private static void write_utf_8() throws IOException {
        //1. Create the OutputStreamWriter object and pass the byte output stream and the specified encoding table name in the construction method
        //OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("10_IO\\utf_8.txt"),"utf-8");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\utf_8.txt"));//Do not specify default use UTF-8
        //2. Use the write method in the OutputStreamWriter object to convert characters into bytes and store them in the buffer (encoding)
        osw.write("Hello");
        //3. Use the method flush in the OutputStreamWriter object to flush the bytes in the memory buffer into the file (the process of writing bytes using byte stream)
        osw.flush();
        //4. Release resources
        osw.close();
    }

}

6.5 understanding diagram of conversion flow: conversion flow is a bridge between bytes and characters

6.6 exercise: converting file codes

Convert GBK encoded text files into UTF-8 encoded text files
code:

package com.wyh.ZhuanHuanLiu;
import java.io.*;

/*
    Exercise: converting file encoding
        Convert GBK encoded text files into UTF-8 encoded text files.

    analysis:
        1.Create an InputStreamReader object and pass the byte input stream and the specified encoding table name GBK in the construction method
        2.Create the OutputStreamWriter object and pass the byte output stream and the specified encoding table name UTF-8 in the construction method
        3.Read the file using the read method in the InputStreamReader object
        4.Use the write method in the OutputStreamWriter object to write the read data to the file
        5.Release resources
 */
public class Task03 {
    public static void main(String[] args) throws IOException {
        //1. Create an InputStreamReader object, and pass the byte input stream and the specified encoding table name GBK in the construction method
        InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\gbk.txt"),"GBK");
        //2. Create the OutputStreamWriter object and pass the byte output stream and the specified encoding table name UTF-8 in the construction method
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\utf_8.txt"),"UTF-8");
        //3. Use the read method in the InputStreamReader object to read the file
        int len = 0;
        while((len = isr.read())!=-1){
            //4. Use the write method in the OutputStreamWriter object to write the read data to the file
            osw.write(len);
        }
        //5. Release resources
        osw.close();
        isr.close();
    }
}

7, Print stream and cache stream

Both buffer stream and print stream appear to improve the efficiency of input-output stream

7.1 what is a print stream?

In the console, we often use system out. print(),System.out.println(),System. out. For functions such as printf (), click the source code of out, and we can find that the static variable public static final PrintStream out = null; The console output is actually calling the method in PrintStream. This class can output data not only to the console, but also to files.
Printstream prints byte stream and PrintWriter prints character stream. Their usage is exactly the same, but PrintWriter is actually a buffer stream, which needs flush() to flush the toilet, while printstream has no cache and prints directly. PrintStream --> FilterOutputStream–> OutputStreamPrintWriter --> Writer
Take PrintStream as an example
Note the print stream. Except for a series of print, pirntf and println methods, other uses are completely consistent with the methods defined in the output stream of OutputStream. However, since you can print, you generally don't need append().
code:

package com.wyh.DaYinYuHuanCun;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;

/**
 * @Deacription Print stream
 * @Author Wang Yuhui
 * @Date 2021/9/4 14:45
 * @Version 1.0
 **/
public class Demo15_DaYin {
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter pw = new PrintWriter("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\a.txt");
        pw.write(54);
        pw.println("sm");
        pw.flush();
        pw.close();
        PrintStream ps = new PrintStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\a.txt");
        ps.println("Weeding day at noon, Qingming River map");
        ps.close();

        PrintWriter pl = new PrintWriter(new FileOutputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\c.txt"));
        pl.println("The bright moon in front of the bed is suspected to be frost on the ground");
        pl.flush();
        pl.close();
    }
}

7.2 buffer flow

When programming or brushing questions, we often read information from the console, such as Scanner input = newScanner(System.in);, If we look at the source code of in, we will find that its implementation is public static final InputStream in = null; It is actually an input stream, system In indicates reading data from the console.
If we often use java to brush questions, we must have seen this statement: BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); This br can also receive input from the console and convert a byte stream to a character stream, but it will be much faster. It can usually solve the problem that Java is too slow and runs overtime.
When using BufferedReader to read the character stream, it can significantly increase the reading efficiency, and provides an additional readLine() method to read one line at a time. Look at a piece of code. The readLine() method will return null after reading. The BufferedReader constructor needs to receive a Reader and can specify the size of the cache when appropriate (default 8192)
code:

package com.wyh.DaYinYuHuanCun;

import java.io.*;

/**
 * @Deacription Cache stream
 * @Author Wang Yuhui
 * @Date 2021/9/4 14:46
 * @Version 1.0
 **/
public class Demo16_HuanCun {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\c.txt"));
        while(true){
            String s = br.readLine();
            if(s == null) break;
            System.out.println(s);
        }
        br.close();
    }
}

7.3 others:

use PrintWriter Refresh the pipeline if necessary
 Byte stream can be converted into print stream in the same way as conversion stream.

7.4 collecting Java exception logs

create documents bug.txt,To collect exceptions. That is, each time an exception is thrown, the exception is written to the document.

code:

package com.wyh;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Deacription: Collect exception logs (Java)
 * @Author Wang Yuhui
 * @Date 2021/9/4 15:03
 * @Version 1.0
 **/
public class Demo17_YiChangRiZhi {
    public static void main(String[] args) throws FileNotFoundException {
        try {
            String s = null;
            s.toString();
        }catch(Exception e){
            PrintWriter pw = new PrintWriter("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\bug.txt");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            pw.println(sdf.format(new Date()));
            e.printStackTrace(pw);
            pw.close();
        }
    }
}

8, Attribute set

8.1 general:

   java.util.Properties inherit from Hashtable to represent a persistent property set. It uses key value structure to store data, and each key and its corresponding value are a string.
This class is also used by many Java classes. For example, when obtaining system Properties, system The getproperties method returns a Properties object.

8.2Properties class

Construction method
public Properties(): create an empty property list
Basic storage methods
public Object setProperty(String key, String value): save a pair of properties
public String getProperty(String key): use the key specified in this property list to search for property values
public Set stringPropertyNames(): a collection of names of all keys
Flow related methods
public void load(InputStream inStream): read key value pairs from byte input stream
Tip: the data in the text must be in the form of key value pairs, which can be separated by spaces, equal signs, colons and other symbols
code:

package com.wyh;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;

/*
    java.util.Properties Set extends hashtable < K, V > implements map < K, V >
    Properties Class represents a persistent set of properties. Properties can be saved in or loaded from a stream.
    Properties A collection is a unique collection combined with IO flows
        You can use the store method in the Properties collection to persistently write the temporary data in the collection to the hard disk for storage
        You can use the load method in the Properties collection to read the files (key value pairs) saved in the hard disk into the collection for use

    Each key and its corresponding value in the attribute list is a string.
        Properties Set is a double column set, and key and value are strings by default
 */
class Demo18_Properties {
    public static void main(String[] args) throws IOException {
        show02();
    }
    /*
            You can use the load method in the Properties collection to read the files (key value pairs) saved in the hard disk into the collection for use
            void load(InputStream inStream)
            void load(Reader reader)
            Parameters:
                InputStream inStream:Byte input stream, cannot read key value pairs containing Chinese
                Reader reader:Character input stream, which can read key value pairs containing Chinese
            Use steps:
                1.Create Properties collection object
                2.Use the load method in the Properties collection object to read the file that holds the key value pair
                3.Traverse the Properties collection
            be careful:
                1.In the file storing key value pairs, the default connection symbol between keys and values can use =, spaces (other symbols)
                2.In the file storing key value pairs, you can use # to annotate, and the annotated key value pairs will no longer be read
                3.In the file where key value pairs are stored, the keys and values are strings by default, without quotes
         */
    private static void show03() throws IOException {
        //1. Create Properties collection object
        Properties prop = new Properties();
        //2. Use the load method in the Properties collection object to read the file that holds the key value pair
        prop.load(new FileReader("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\prop.txt"));
        //prop.load(new FileInputStream("09_IOAndProperties\\prop.txt"));
        //3. Traverse the Properties collection
        Set<String> set = prop.stringPropertyNames();
        for (String key : set) {
            String value = prop.getProperty(key);
            System.out.println(key+"="+value);
        }
    }
    /*
        You can use the store method in the Properties collection to persistently write the temporary data in the collection to the hard disk for storage
        void store(OutputStream out, String comments)
        void store(Writer writer, String comments)
        Parameters:
            OutputStream out:Byte output stream, cannot write Chinese
            Writer writer:Character output stream, can write Chinese
            String comments:Note, used to explain what the saved file is used for
                    Can not use Chinese, will produce garbled code, the default is Unicode coding
                    Empty string is generally used

        Use steps:
            1.Create the Properties collection object and add data
            2.Create a byte output stream / character output stream object, and bind the destination to be output in the construction method
            3.Use the store method in the Properties collection to persistently write the temporary data in the collection to the hard disk for storage
            4.Release resources
     */
    private static void show02() throws IOException {
        //1. Create the Properties collection object and add data
        Properties prop = new Properties();
        prop.setProperty("Zhao Liying","168");
        prop.setProperty("Delireba","165");
        prop.setProperty("Gulinaza","160");

        //2. Create byte output stream / character output stream object, and bind the destination to be output in the construction method
        FileWriter fw = new FileWriter("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\prop.txt");

        //3. Use the store method in the Properties collection to persistently write the temporary data in the collection to the hard disk for storage
        prop.store(fw,"save data");

        //4. Release resources
        fw.close();

        //prop.store(new FileOutputStream("09_IOAndProperties\\prop2.txt"),"");
    }

    /*
        Use the Properties collection to store data, and traverse to get the data in the Properties collection
        Properties Set is a double column set, and key and value are strings by default
        Properties Collections have some unique methods of manipulating strings
            Object setProperty(String key, String value) Call the put method of Hashtable.
            String getProperty(String key) Find the value value through the key. This method is equivalent to the get(key) method in the Map collection
            Set<String> stringPropertyNames() Returns the key set in this property list, where the key and its corresponding value are strings. This method is equivalent to the keySet method in the Map collection
     */
    private static void show01() {
        //Create Properties collection object
        Properties prop = new Properties();
        //Use setProperty to add data to the collection
        prop.setProperty("Zhao Liying","168");
        prop.setProperty("Delireba","165");
        prop.setProperty("Gulinaza","160");
        //prop.put(1,true);

        //Use stringPropertyNames to take out the keys in the Properties collection and store them in a Set collection
        Set<String> set = prop.stringPropertyNames();

        //Traverse the Set set and take out each key of the Properties Set
        for (String key : set) {
            //Use the getProperty method to obtain value through key
            String value = prop.getProperty(key);
            System.out.println(key+"="+value);
        }
    }
}

9, Serialization (unfamiliar)

9.1 what is it?

Serialization refers to turning a Java object into binary content, which is essentially a byte [] array. Why serialize Java objects? Because after serialization, you can save byte [] to a file or transfer byte [] to a remote through the network. In this way, it is equivalent to storing Java objects in a file or transmitting them through the network. Orderly serialization means deserialization, That is, a binary content (i.e. byte [] array) can be changed back to a Java object. With deserialization, the byte [] array saved to a file can be "changed back" to a Java object, or byte [] can be read from the network and "changed back" to a Java object. The core function is to save and rebuild the object state. (the core point of the whole process is the object state and description information saved in the byte stream)

9.2 diagram:###9.3 JSON / XML data transfer:

Before data transmission (also known as network transmission), Java objects are serialized into json/xml files through the sequence tool class.
After data transmission (also known as network transmission), the json/xml file is deserialized into the object of the corresponding language

9.4 serialization advantages:

① convert the object into a byte stream and store it on the hard disk. When the JVM stops, the byte stream will wait silently on the hard disk for the next start of the JVM. The serialized object is deserialized into the original object, and the serialized binary sequence can reduce the storage space (permanently save the object).
② objects serialized into byte stream form can be transmitted on the network (binary form), which is convenient for network transmission.
③ objects can be passed between processes through serialization.

9.5 Java implements the process of serialization and deserialization

1. Necessary requirements for serialization:
Only objects of classes that implement the Serializable or Externalizable interface can be serialized into byte sequences. (if not, an exception will be thrown)
2. API for serialization and deserialization in JDK:
      ①java.io.ObjectInputStream: object input stream.
The readObject() method of this class reads the byte sequence from the input stream, then deserializes the byte sequence into an object and returns it.
       ②java.io.ObjectOutputStream: object output stream.
The writeObject(Object obj) method of this class serializes the incoming obj object and writes the resulting byte sequence to the target output stream for output.
Serialization and deserialization code examples
3. Serialization of some attributes (see the document)

9.6 precautions for serialization and deserialization:

① when serializing, only the state of the object is saved, regardless of the method of the object;
② when a parent class implements serialization, the child class automatically implements serialization without explicitly implementing the Serializable interface;
③ when the instance variable of an object references other objects, the reference object is also serialized when the object is serialized;
④ not all objects can be serialized. There are many reasons why not, such as:
For security reasons, for example, an object has private, public and other fields. For an object to be transmitted, such as writing to a file or RMI transmission, the private and other fields of the object are not protected during serialization and transmission;
For resource allocation reasons, such as socket and thread classes, if they can be serialized, transmitted or saved, they cannot be reallocated, and it is not necessary to implement them in this way;
⑤ member data declared as static and transient types cannot be serialized. Because static represents the state of the class and transient represents the temporary data of the object.
⑦ many basic classes of Java have implemented serializable interfaces, such as String,Vector, etc. However, there are some that do not implement the serializable interface;
code:

package com.wyh.XuLieHua;

import java.io.Serializable;
import java.util.List;

/**
 * @Deacription Student entity class
 * @Author Wang Yuhui
 * @Date 2021/9/4 21:03
 * @Version 1.0
 **/
public class Student implements Serializable {
    /**
     * Student number
     */
    private String stuNum;
    /**
     * full name
     */
    private String stuName;
    /**
     * Teacher name: a student can have more than one teacher
     */
    private List<String> teacherList;
    //Nonparametric construction method
    public Student() {
    }
    //Full parameter construction method
    public Student(String stuNum, String stuName, List<String> teacherList) {
        this.stuNum = stuNum;
        this.stuName = stuName;
        this.teacherList = teacherList;
    }
    @Override
    public String toString() {
        return "Student{" +
                "stuNum='" + stuNum + '\'' +
        ", stuName='" + stuName + '\'' +
                ", teacherList=" + teacherList +
                '}';
    }
    public String getStuNum() {
        return stuNum;
    }
    public void setStuNum(String stuNum) {
        this.stuNum = stuNum;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public List<String> getTeacherList() {
        return teacherList;
    }
    public void setTeacherList(List<String> teacherList) {
        this.teacherList = teacherList;
    }

}
package com.wyh.XuLieHua;

import java.io.*;

/**
 * @Deacription Tool classes for serialization and deserialization
 * @Author Wang Yuhui
 * @Date 2021/9/4 21:07
 * @Version 1.0
 **/
public class MySerializeUtil {
    /**
     * Serializes the object into the specified file
     * @param obj
     * @param fileName
     */
    public static void mySerialize(Object obj,String fileName) throws IOException {
        OutputStream out=new FileOutputStream(fileName);
        ObjectOutputStream objOut=new ObjectOutputStream(out);
        objOut.writeObject(obj);
        objOut.close();
    }
    /**
     * Deserializes an object from the specified file
     * @param fileName
     * @return
     */
    public static Object myDeserialize(String fileName) throws IOException,ClassNotFoundException {
        InputStream in=new FileInputStream(fileName);
        ObjectInputStream objIn=new ObjectInputStream(in);
        Object obj=objIn.readObject();
        return obj;
    }
}
package com.wyh.XuLieHua;

import java.util.ArrayList;
import java.util.List;

/**
 * @Deacription Test class
 * @Author Wang Yuhui
 * @Date 2021/9/4 21:06
 * @Version 1.0
 **/
public class MainTest {
    public static void main(String[] args) {
        List<String> teacherList=new ArrayList<>();
        teacherList.add("reverend void ");
        teacherList.add("Jia dairu");
        Student stu1=new Student("1001", "Jia Baoyu", teacherList);
        System.out.println("Original object:"+stu1);
        String fileName="D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\a.txt";
        try {
            //Object serialization 
            MySerializeUtil.mySerialize(stu1, fileName);
            System.out.println("Serialization of original object completed! OK!");
             //Deserialization of objects
            Object obj=MySerializeUtil.myDeserialize(fileName);
            if(obj instanceof Student){
                Student stuNew= (Student) obj;
                System.out.println("Object after deserialization:"+stuNew);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
package com.wyh.XuLieHua;

import java.io.*;

/**
 * @Deacription serialize
 * @Author Wang Yuhui
 * @Date 2021/9/4 15:58
 * @Version 1.0
 **/
public class Demo19_XuLieHua {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // Serialization: object to byte
        /*Book b = new Book("Golden Apple "," Golden Apple planting process ");
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\bug.txt"));
        os.writeObject(b);
        os.close();*/

        // Deserialization: byte to object
        ObjectInputStream os = new ObjectInputStream(new FileInputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\bug.txt"));
        Book o =(Book) os.readObject();
        System.out.println(o);
    }

    static class Book implements Serializable{
        private String name;
        private String info;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getInfo() {
            return info;
        }

        public void setInfo(String info) {
            this.info = info;
        }

        public Book() {
        }

        public Book(String name, String info) {
            this.name = name;
            this.info = info;
        }

        @Override
        public String toString() {
            return "Book{" +
                    "name='" + name + '\'' +
                    ", info='" + info + '\'' +
                    '}';
        }
    }
}

10, Handling of IO exceptions

10.1 JDK7 pretreatment

In jdk1 Before 7, trycatchfinally was used to handle exceptions in the flow
Format:
      try{
Abnormal code may be generated
} catch (exception class variable name){
Exception handling logic
      }finally{
Must specify the code
Resource release
      }
code:

package com.wyh.IOYiChang;
import java.io.FileWriter;
import java.io.IOException;

/*
    In jdk1 Before 7, try catch finally was used to handle exceptions in the stream
    Format:
        try{
            Abnormal code may be generated
        }catch(Exception class (variable name){
            Exception handling logic
        }finally{
            Must specify the code
            Resource release
        }
 */
public class Demo20_TryCatch {
    public static void main(String[] args) {
        //Increase the scope of variable fw so that finally can be used
        //Variables can be defined without values, but they must be used with values
        //fw = new FileWriter("09_IOAndProperties\g.txt",true);  Execution failed, FW has no value, FW Close will report an error
        FileWriter fw = null;
        try{
            //Abnormal code may be generated
            fw = new FileWriter("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\b.txt",true);
            for (int i = 0; i <10 ; i++) {
                fw.write("HelloWorld"+i+"\r\n");
            }
        }catch(IOException e){
            //Exception handling logic
            System.out.println(e);
        }finally {
            //Must specify the code
            //Failed to create the object. The default value of fw is null. Null cannot call the method, and NullPointerException will be thrown. It is necessary to add a judgment that null is not releasing the resource
            if(fw!=null){
                try {
                    //fw. The close method declaration throws an IOException object, so we will handle the exception object, either throw or try catch
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

10.2 handling of JDK7

New features of JDK7
A () can be added after the try, and the flow object can be defined in parentheses. Then the scope of the flow object is valid in the try. After the code in the try is executed, the flow object will be released automatically without writing finally
Format:
Try (define flow object; define flow object...){
Abnormal code may be generated
} catch (exception class variable name){
Exception handling logic
      }
code:

package com.wyh.IOYiChang;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
    JDK7 New features of
    A () can be added after the try, and the flow object can be defined in parentheses
    Then the scope of this stream object is valid in try
    try After the code in is executed, the stream object will be automatically released without writing finally
    Format:
        try(Define flow objects; Define flow object...) {
            Abnormal code may be generated
        }catch(Exception class (variable name){
            Exception handling logic
        }
 */
public class Demo21_JDK7 {
    public static void main(String[] args) {
        try(//1. Create a byte input stream object and bind the data source to be read in the construction method
            FileInputStream fis = new FileInputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\c.txt");
            //2. Create a byte output stream object and bind the destination to be written in the construction method
            FileOutputStream fos = new FileOutputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\b.txt");){

            //Abnormal code may be generated
            //Read one byte at a time and write one byte at a time
            //3. Use the read method in the byte input stream object to read the file
            int len = 0;
            while((len = fis.read())!=-1){
                //4. Use the write method in the byte output stream to write the read bytes to the destination file
                fos.write(len);
            }
        }catch (IOException e){
            //Exception handling logic
            System.out.println(e);
        }
    }
}

10.3 improvement of jdk9

New features of JDK9
The stream object can be defined at the front of the try. The name of the stream object (variable name) can be directly introduced into the () at the back of the try. After the try code is executed, the stream object can also be released without writing finally
Format:
      Aa=newA();
      Bb=newB();
      try(a,b){
Abnormal code may be generated
} catch (exception class variable name){
Exception handling logic
      }
Tip: the created object must implement Closeable
code:

package com.wyh.IOYiChang;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
    JDK9 New features
    try The front edge of the can define a flow object
    The name of the stream object (variable name) can be directly introduced into the () after the try
    After the try code is executed, the stream object can also be released without writing finally
    Format:
        A a = new A();
        B b = new B();
        try(a,b){
            Abnormal code may be generated
        }catch(Exception class (variable name){
            Exception handling logic
        }
 */
public class Demo22_JDK9 {
    public static void main(String[] args) throws IOException {
        //1. Create a byte input stream object and bind the data source to be read in the construction method
        FileInputStream fis = new FileInputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\c.txt");
        //2. Create a byte output stream object and bind the destination to be written in the construction method
        FileOutputStream fos = new FileOutputStream("D:\\eclipse-workspace\\C_XX_HeXinLeiKu\\c_XX_IO\\IO\\a.txt");
        CloseDemo d = new CloseDemo();
        try(fis;fos;d){
            //Read one byte at a time and write one byte at a time
            //3. Use the read method in the byte input stream object to read the file
            int len = 0;
            while((len = fis.read())!=-1){
                //4. Use the write method in the byte output stream to write the read bytes to the destination file
                fos.write(len);
            }
        }catch (IOException e){
            System.out.println(e);
        }
        //fos.write(1);//Stream Closed
    }

    // Tip: the created object must implement Closeable
    static class CloseDemo implements Closeable {
        @Override
        public void close() throws IOException {
            System.out.println("Close Method was called");
        }
    }
}

11, Comprehensive exercise

This exercise will take some time. Let's talk about it later.

Reference: it's some time since I took notes. Please forgive me if my notes obviously learn from your content. (my memory is very poor. When I first wrote notes, the reference documents may not be complete)
I don't know what it is:
https://www.cnblogs.com/zhangminghui/p/4484579.html
Data download link (notes + code + others): Baidu online disk
Link: https://pan.baidu.com/s/1Q8SGVvJKloeeovT1iognfg
Extraction code: 1111
Thank you for reading. I wish you all the best from now on.

Keywords: Java Back-end

Added by andynick on Wed, 15 Dec 2021 19:54:44 +0200