JAVA learning notes (Chapter 8 file and I/O flow)

1, File object

1. Create file object

public class TestFile {  
    public static void main(String[] args) {
        // Absolute path
        File f1 = new File("d:/LOLFolder");
        System.out.println("f1 Absolute path to:" + f1.getAbsolutePath());

        // Relative path, relative to the working directory, if in eclipse, is the project directory
        File f2 = new File("LOL.exe");
        System.out.println("f2 Absolute path to:" + f2.getAbsolutePath());
  
        // Create a file object with f1 as the parent directory
        File f3 = new File(f1, "LOL.exe");  
        System.out.println("f3 Absolute path to:" + f3.getAbsolutePath());
    }
}

2. Common methods of documents

public class TestFile {  
    public static void main(String[] args) {  
        File f = new File("d:/LOLFolder/LOL.exe");
        System.out.println("The current file is:" +f);
        //Does the file exist
        System.out.println("Determine whether there is:"+f.exists());         
        //Is it a folder
        System.out.println("Determine whether it is a folder:"+f.isDirectory());          
        //Is it a file (not a folder)
        System.out.println("Determine whether it is a file:"+f.isFile());         
        //file length
        System.out.println("Get the length of the file:"+f.length());          
        //Last modification time of file
        long time = f.lastModified();
        Date d = new Date(time);
        System.out.println("Get the last modification time of the file:"+d);
        //Set the file modification time to 08:00:00 on January 1, 1970
        f.setLastModified(0);         
        //File rename
        File f2 =new File("d:/LOLFolder/DOTA.exe");
        f.renameTo(f2);
        System.out.println("hold LOL.exe Renamed DOTA.exe");         
        System.out.println("Note: you need to D:\\LOLFolder There is one LOL.exe,\r\n Then you can see the corresponding file length, modification time and other information");
    }
}
public class TestFile {  
    public static void main(String[] args) throws IOException {  
        File f = new File("d:/LOLFolder/skin/garen.ski");  
        // Returns all files in the current folder (excluding sub files and sub folders) in the form of string array
        f.list();  
        // Returns all files in the current folder (excluding sub files and sub folders) in the form of file array
        File[]fs= f.listFiles();  
        // Returns the folder where the retrieval is located as a string
        f.getParent(); 
        // Return to get the folder as a file
        f.getParentFile();
        // Create a folder. If the parent folder skin does not exist, the creation is invalid
        f.mkdir();  
        // Create a folder. If the parent folder skin does not exist, the parent folder will be created
        f.mkdirs();  
        // Create an empty file. If the parent folder skin does not exist, an exception will be thrown
        f.createNewFile();
        // Therefore, before creating an empty file, the parent directory is usually created
        f.getParentFile().mkdirs(); 
        // List all drive letters c: d: e: etc
        f.listRoots();  
        // Delete file
        f.delete();  
        // Delete files at the end of the JVM, which is often used to delete temporary files
        f.deleteOnExit();  
    }
}

2, What is flow

What is a stream? A stream is a series of data.

When there is data interaction between different media, JAVA uses stream to realize it.
The data source can be a file, a database, a network or even other programs

For example, reading the data of a file into a program is called an input stream from the perspective of the program
Input stream: InputStream
Output stream: OutputStream

1. Byte stream

When it comes to bytes, ASCII code is indispensable. The ASCII code table is shown below.

(1) Reads the contents of the file as a byte stream

InputStream is not only a byte input stream, but also an abstract class. It only provides method declarations, not specific implementations of methods.
FileInputStream is a subclass of InputStream. Take FileInputStream as an example to read files.

public class TestStream {  
    public static void main(String[] args) {
        try {
            //Prepare the file lol.txt, where the contents are AB and the corresponding ASCII are 65 and 66 respectively
            File f =new File("d:/lol.txt");
            //Create a file based input stream
            FileInputStream fis =new FileInputStream(f);
            //Create a byte array whose length is the length of the file
            byte[] all =new byte[(int) f.length()];
            //Reads all the contents of the file as a byte stream
            fis.read(all);
            for (byte b : all) {
                //Print out 65 66
                System.out.println(b);
            }             
            //Every time the stream is used, it should be closed
            fis.close();              
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }          
    }
}

(2) Writes data to a file as a byte stream

OutputStream is not only a byte output stream, but also an abstract class. It only provides method declarations, not specific implementations of methods.
FileOutputStream is a subclass of OutputStream. Take FileOutputStream as an example to write data to a file.

public class TestStream { 
    public static void main(String[] args) {
        try {
            // Prepare file lol2 Txt the contents are empty
            File f = new File("d:/lol2.txt");
            // Prepare a byte array with a length of 2 and initialize it with 88 and 89. The corresponding characters are x and Y respectively
            byte data[] = { 88, 89 }; 
            // Create a file based output stream
            FileOutputStream fos = new FileOutputStream(f);
            // Write data to output stream
            fos.write(data);
            // Close output stream
            fos.close();             
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }
}

2. How to close the flow

All streams, whether input or output, should be closed after use. If it is not closed, it will waste resources. When the equivalent is large, it will affect the normal development of business.

(1) Close in try

Close the file input stream in the scope of try. In the previous examples, this method is used. This has a disadvantage;
If the file does not exist, or an exception is thrown due to a problem when reading, this line of code to close the flow will not be executed, resulting in a huge hidden danger of resource occupation. Not recommended.

(2) Close in finally

This is the standard way to close the flow:
① first, declare the reference of the stream outside the try. If it is declared inside the try, its scope cannot reach finally;
② before finally closing, judge whether the reference is empty;
③ when closing, try catch again.

public class TestStream { 
    public static void main(String[] args) {
        File f = new File("d:/lol.txt");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(f);
            byte[] all = new byte[(int) f.length()];
            fis.read(all);
            for (byte b : all) {
                System.out.println(b);
            } 
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Close the flow in finally
            if (null != fis)
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        } 
    }
}

(3) How to use try()

Define the stream in try(). When try,catch or finally ends, it will be closed automatically. This way of writing code is called try with resources, which is a technology supported from JDK7.
All streams implement an interface called autoclosable. Any class that implements this interface can be instantiated in try(). It will be automatically closed at the end of try, catch and finally to recycle relevant resources.

3. Character stream

Reader character input stream
Writer character output stream
It is specially used to read and write data in the form of characters. The way character stream reads and writes files is the same as byte stream, just change two keywords.

4. Coding problem

(1) Common coding

The coding methods frequently contacted after work are as follows:
ISO-8859-1 ASCII} numbers and Western European letters
GBK GB2312 BIG5 Chinese
UNICODE (unified code, universal code)
among
ISO-8859-1 contains ASCII;
GB2312 is simplified Chinese, BIG5 is traditional Chinese, and GBK includes both simplified, traditional and Japanese;
UNICODE includes all the characters, including Chinese, English, Tibetan, French and all the characters in the world.

However, if the data is stored completely according to UNICODE, it will be a great waste. In this case, various sub codes of UNICODE appear. For example, UTF-8 uses one byte for numbers and letters and three bytes for Chinese characters, which reduces the waste of space. Generally speaking, UTF-8 is a common method.

(2) Java uses Unicode

Write in Chinese characters in java source code will become characters in JVM after execution.
These Chinese characters are encoded in UNICODE The UNICODE corresponding to the word "Zhong" is 4E2D, so the data actually saved in memory is 0x4E2D in hexadecimal, that is, 20013 in decimal.

(3) Read Chinese correctly with FileInputStream byte stream

In order to correctly read Chinese content:
① it is necessary to know which encoding method is used to save characters in the text;
② after using the byte stream to read the text, use the corresponding coding method to identify these numbers and get the correct characters. For example, if the content in a file is in the characters, the coding method is GBK, and then use the GBK coding method to identify D6D0, you can get the correct characters

Using String(all,"GBK"), you can change the encoding mode of all string to GBK mode. Of course, you can also change to "BIG5", "GBK", "GB2312", "UTF-8", "UTF-16", "UTF-32" and other modes.

(4) Read Chinese correctly with FileReader character stream

FileReader gets characters, so it must have recognized bytes as characters according to some coding. The encoding method used by FileReader is charset The return value of defaultcharset() is GBK if it is a Chinese operating system
The encoding method of FileReader cannot be set manually. In order to use other encoding methods, InputStreamReader can only be used instead. For example:

new InputStreamReader(new FileInputStream(f),Charset.forName("UTF-8")); 

For example:

public class TestStream { 
    public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException {
        File f = new File("E:\\project\\j2se\\src\\test.txt");
        System.out.println("Default encoding method:"+Charset.defaultCharset());
        //FileReader gets characters, so it must have recognized bytes as characters according to some coding
        //The encoding method used by FileReader is charset The return value of defaultcharset() is GBK if it is a Chinese operating system
        try (FileReader fr = new FileReader(f)) {
            char[] cs = new char[(int) f.length()];
            fr.read(cs);
            System.out.printf("FileReader The default encoding method is used%s,The recognized characters are:%n",Charset.defaultCharset());
            System.out.println(new String(cs));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //FileReader cannot set the encoding method manually. In order to use other encoding methods, InputStreamReader can only be used instead
        //And use new inputstreamreader (New FileInputStream (f), charset forName("UTF-8"));  Such a form
        try (InputStreamReader isr = new InputStreamReader(new FileInputStream(f),Charset.forName("UTF-8"))) {
            char[] cs = new char[(int) f.length()];
            isr.read(cs);
            System.out.printf("InputStreamReader Specify encoding method UTF-8,The recognized characters are:%n");
            System.out.println(new String(cs));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }         
    }
}

5. Buffer flow

Taking the hard disk as an example, the disadvantages of byte stream and character stream are as follows:
Every time I read and write, I will access the hard disk. If the frequency of reading and writing is high, its performance is poor.

In order to solve the above disadvantages, cache stream is used.
When the cache stream is read, more data will be read into the cache at one time. Each read in the future will be accessed in the cache until the data in the cache is read, and then read into the hard disk.

When the cache stream writes data, it will first write the data to the cache until the cache reaches a certain amount, and then write these data to the hard disk together. According to this operation mode, the hard disk will not be accessed every byte written like byte stream and character stream, thus reducing IO operations.

(1) Use buffered stream to read and write data

BufferedReader} can read one row of data at a time

public class TestStream {  
    public static void main(String[] args) {
        File f = new File("d:/lol.txt");
        // Create file character stream
        // The cache stream must be based on an existing stream
        try (
                FileReader fr = new FileReader(f);
                BufferedReader br = new BufferedReader(fr);
            )
        {
            while (true) {
                // Read one line at a time
                String line = br.readLine();
                if (null == line)
                    break;
                System.out.println(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
    }
}

PrintWriter} can write out one row of data at a time

public class TestStream {   
    public static void main(String[] args) {
        // To file lol2 Txt
        File f = new File("d:/lol2.txt");          
        try (
                // Create file character stream
                FileWriter fw = new FileWriter(f);
                // The cache stream must be based on an existing stream              
                PrintWriter pw = new PrintWriter(fw);              
        ) {
            pw.println("garen kill teemo");
            pw.println("teemo revive after 1 minutes");
            pw.println("teemo try to garen, but killed again");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }
}

(2)flush

Sometimes, you need to write data to the hard disk immediately, rather than wait until the cache is full. You need to use flush at this time.

public class TestStream {
    public static void main(String[] args) {
        //To file lol2 Txt
        File f =new File("d:/lol2.txt");
        //Create file character stream
        //The cache stream must be based on an existing stream
        try(FileWriter fr = new FileWriter(f);PrintWriter pw = new PrintWriter(fr);) {
            pw.println("garen kill teemo");
            //Force the data in the cache to be written to the hard disk, regardless of whether the cache is full or not
                pw.flush();           
            pw.println("teemo revive after 1 minutes");
                pw.flush();
            pw.println("teemo try to garen, but killed again");
                pw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

6. Data flow

DataInputStream data input stream
DataOutputStream data output stream

Use writeUTF() and readUTF() of data stream to read and write data in formatted order

Note: to read a file with DataInputStream, the file must be written out by DataOutputStream, otherwise EOFException will occur, because DataOutputStream will make some special marks when writing out, and only DataInputStream can read it successfully.

public class TestStream {      
    public static void main(String[] args) {
        write();
        read();
    }
 
    private static void read() {
        File f =new File("d:/lol.txt");
        try (
                FileInputStream fis  = new FileInputStream(f);
                DataInputStream dis =new DataInputStream(fis);
        ){
            boolean b= dis.readBoolean();
            int i = dis.readInt();
            String str = dis.readUTF();
             
            System.out.println("Read Boolean:"+b);
            System.out.println("Read integer:"+i);
            System.out.println("Read string:"+str); 
        } catch (IOException e) {
            e.printStackTrace();
        }         
    }
 
    private static void write() {
        File f =new File("d:/lol.txt");
        try (
                FileOutputStream fos  = new FileOutputStream(f);
                DataOutputStream dos =new DataOutputStream(fos);
        ){
            dos.writeBoolean(true);
            dos.writeInt(300);
            dos.writeUTF("123 this is gareen");
        } catch (IOException e) {
            e.printStackTrace();
        }         
    }
}

7. Object flow

Object streaming means that an object can be directly transmitted to other media in the form of streaming, such as hard disk. An object is transmitted as a stream, which is called serialization. The class corresponding to the object must implement the Serializable interface.

//To save the Hero object directly to a file, make sure that the Hero class implements the Serializable interface
class Hero implements Serializable {
    //Indicates the current version of this class. If there are changes, such as newly designed attributes, this version number should be modified
    private static final long serialVersionUID = 1L;
    public String name;
    public float hp;
 
}

public class TestStream {    
    public static void main(String[] args) {
        Hero h = new Hero();
        h.name = "garen";
        h.hp = 616;          
        //Prepare a file to save the object
        File f =new File("d:/garen.lol"); 
        try(
            //Create object output stream
            FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream oos =new ObjectOutputStream(fos);
            //Create object input stream              
            FileInputStream fis = new FileInputStream(f);
            ObjectInputStream ois =new ObjectInputStream(fis);
        ) {
            oos.writeObject(h);
            Hero h2 = (Hero) ois.readObject();
            System.out.println(h2.name);
            System.out.println(h2.hp);               
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }            
    }
}

8. Console I / O

(1) System.out and system in

        System.out is commonly used to output data on the console
        System.in can enter data from the console

public class TestStream { 
    public static void main(String[] args) {
        // Console input 
        try (InputStream is = System.in;) {
            while (true) {
                // You can see by typing in a and then typing back
                // 97 13 10
                // 97 is the ASCII code of a
                // 13 and 10 correspond to carriage return and line feed respectively
                int i = is.read();
                System.out.println(i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(2)Scanner

Use system in. Although read can read data, it is very inconvenient. Using Scanner, you can read line by line.

Scanner() has been used before. Here is an example.

public class TestStream {    
    public static void main(String[] args) {         
        Scanner s = new Scanner(System.in);             
        while(true){
        String line = s.nextLine();
        System.out.println(line);
        }         
    }
}

9. Relationship between flows

 

Keywords: Java Back-end

Added by tave on Fri, 14 Jan 2022 07:32:25 +0200