java Basics - day09_ Byte stream, character stream

Article catalog

02_IO overview (concept & classification)

03_ Everything is byte

No matter what stream object, binary data is always transmitted

04_ Byte output stream_ OutputStream class & introduction to fileoutputstream class

05_ Byte output stream writes data to file

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
    java.io.OutputStream:Byte output stream
        This abstract class is a superclass representing all classes of the output byte stream.

    Some common member methods of subclasses are defined
        - public void close() : Close this output stream and release any system resources associated with it.
        - 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 to this output stream starting with the offset off.
        - public abstract void write(int b) : Outputs the specified byte stream.

    java.io.FileOutputStream extends OutputStream
    FileOutputStream:File byte output stream
    Function: write data in memory to files on hard disk

    Construction method:
        FileOutputStream(String name)Creates an output file stream that writes data to a file with the specified name.
        FileOutputStream(File file) Creates a File output stream that writes data to the File represented by the specified File object.
        Parameters: purpose of writing data
            String name:Destination is the path to a file
            File file:Destination is a file
        Function of construction method:
            1.Create a FileOutputStream object
            2.Creates an empty file based on the file / file path passed in the construction method
            3.Will point the FileOutputStream object to the created file

    Principle of writing data (memory - > hard disk)
        java Program - > JVM (Java virtual machine) -- > OS (operating system) -- > OS calls the method of writing data -- > writes the data to the file

    Use steps of byte output stream (key points):
        1.Create a FileOutputStream object to construct the destination of write data in the method
        2.Call the method write in the FileOutputStream object to write the data to the file
        3.Release resources (stream usage will occupy a certain amount of memory, and the memory should be emptied after use, which is the efficiency of the provider)
 */
public class Demo02File {
    public static void main(String[] args) {
        write_txt();
    }
    private static void write_txt() {
        try {
            //1. Create a FileOutputStream object to construct the destination of the written data in the method
            FileOutputStream fos=new FileOutputStream("a.txt");
            //2. Call the method write in the FileOutputStream object to write the data to the file
            //public abstract void write(int b): outputs the specified byte stream.
            fos.write(97);
            //  3. Release resources (stream usage will occupy a certain amount of memory, and the memory should be emptied after use, so the efficiency of the provider)
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
/*
* -----------------------
* Finally, a text is created, and a
* -----------------------
* */
    }
}

06_ The principle of file storage and notepad opening

07_ The method of writing multiple bytes in byte output stream


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

/*
    To write multiple bytes at a time:
        - 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 to this output stream starting at offset off.
 */
public class Demo02File {
    public static void main(String[] args) throws IOException {
        //Create the FileOutputStream object and bind the destination of the data to be written in the construction method
        FileOutputStream fos = new FileOutputStream(new File("09_IOAndProperties\\b.txt"));
        //Call the method write in the FileOutputStream object to write the data to the file
        //Display 100 in the file, write three bytes, explain one by one
        fos.write(49);
        fos.write(48);
        fos.write(48);

        /*
            public void write(byte[] b): Writes b.length bytes from the specified byte array to this output stream.
            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 a negative number, the first byte and the second byte will form a Chinese display and query the system's default code table (GBK)
         */
        byte[] bytes = {65,66,67,68,69};//ABCDE
        //byte[] bytes = {-65,-66,-67,68,69}; / / bake E
        fos.write(bytes);

        /*
            public void write(byte[] b, int off, int len) : Write part of byte array to 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 String class to convert a String to 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]
        //utf-8 three bytes one Chinese, gbk two
        fos.write(bytes2);
        //Release resources
        fos.close();
    }
}

08_ Continuation and newline of byte output stream


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

/*
    To write multiple bytes at a time:
        - 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 to this output stream starting at offset off.
 */
public class Demo02File {
    public static void main(String[] args) throws IOException {
        //Create the FileOutputStream object and bind the destination of the data to be written in the construction method
        FileOutputStream fos = new FileOutputStream(new File("09_IOAndProperties\\b.txt"));
        //Call the method write in the FileOutputStream object to write the data to the file
        //Show 100 in file, write three bytes
        fos.write(49);
        fos.write(48);
        fos.write(48);

        /*
            public void write(byte[] b): Writes b.length bytes from the specified byte array to this output stream.
            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 a negative number, the first byte and the second byte will form a Chinese display and query the system's default code table (GBK)
         */
        byte[] bytes = {65,66,67,68,69};//ABCDE
        //byte[] bytes = {-65,-66,-67,68,69}; / / bake E
        fos.write(bytes);

        /*
            public void write(byte[] b, int off, int len) : Write part of byte array to 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 String class to convert a String to 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();
    }
}

09_ Byte input stream_ InputStream class & introduction to FileInputStream class

10_ Byte input stream reads byte data

11_ The principle of byte input stream reading one byte at a time

12_ Byte input stream reads multiple bytes at a time

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

/*
    java.io.InputStream:Byte input stream
    This abstract class is a superclass representing all classes of the byte input stream.

    The common methods of all subclasses are defined:
         int read()Reads the next byte of data from the input stream.
         int read(byte[] b) A certain number of bytes are read from the input stream and stored in the buffer array b.
         void close() Close this input stream and release all system resources associated with it.

    java.io.FileInputStream extends InputStream
    FileInputStream:File byte input stream
    Function: read the data in the hard disk file and use it in memory

    Construction method:
        FileInputStream(String name)
        FileInputStream(File file)
        Parameters: reading the data source of a file
            String name:Path to file
            File file:file
        Function of construction method:
            1.A FileInputStream object is created
            2.The FileInputStream object specifies the file to be read in the constructor

    Principle of reading data (hard disk -- > memory)
        java Program -- > JVM -- > OS -- > OS read data method -- > read file

    Use steps of byte input stream (key points):
        1.Create the FileInputStream object, bind the data source to be read in the construction method
        2.Use the method read in the FileInputStream object to read the file
        3.Release resources
 */
public class Demo01InputStream {
    public static void main(String[] args) throws IOException {
        //1. Create a FileInputStream object and bind the data source to be read in the construction method
        FileInputStream fis = new FileInputStream("09_IOAndProperties\\c.txt");
        //2. Use the method read in the FileInputStream object to read the file
        //int read() reads a byte in the file and returns, - 1
        /*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 the above read file is a repetitive process, so loop optimization can be used
            Do not know how many bytes are in the file, use while loop
            while Loop end condition, end when reading to - 1

            Boolean expression (len= fis.read ())!=-1
                1.fis.read():Read a byte
                2.len = fis.read():Assign the bytes read to the variable len
                3.(len = fis.read())!=-1:Judge whether the variable len is not equal to - 1
         */
        int len = 0; //Record bytes read
        while((len = fis.read())!=-1){
            System.out.print(len);//abc
            /*
            * -----------------------
            * Don't write directly fis.read() because it has been executing, half of the data will be lost if the variable is not used to accept the result
            * -----------------------
            * */
        }

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

13_ Practice_ File copy

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

/*
    File copying exercise: reading and writing

    to make clear:
        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 method write in byte output stream to write the bytes read to the destination file
        5.Release resources
 */
public class Demo01CopyFile {
    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:\\1.jpg");
        //2. Create a byte output stream object and bind the destination to be written in the construction method
        FileOutputStream fos = new FileOutputStream("d:\\1.jpg");
        //How to read one byte at a time and write one byte at a time
        //3. Read the file using the method read in the byte input stream object
        /*int len = 0;
        while((len = fis.read())!=-1){
            //4.Use the method write in byte output stream to write the bytes read to the destination file
            fos.write(len);
        }*/

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

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

}

14_ Using byte stream to read Chinese

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

/*
    Use byte stream to read Chinese file
    1 Chinese
        GBK:Takes two bytes
        UTF-8:Take up 3 bytes
 */
public class Demo01InputStream {
    public static void main(String[] args) throws IOException {
        FileInputStream fis = new FileInputStream("09_IOAndProperties\\c.txt");
        int len = 0;
        while((len = fis.read())!=-1){
            System.out.println((char)len);
        }
        /*
        * -----------------------
        * There will be garbled code problems in direct reading. Character files need to use character reading methods
        * -----------------------
        * */
        fis.close();
    }
}

15_ Character input stream_ Reader class & FileReader class introduction

16_ Character input stream reading character data

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 member methods:
        int read() Reads a single character and returns.
        int read(char[] cbuf)Read more than one character at a time, read the characters into the array.
        void close() Close the stream 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)
        Parameters: reading the data source of a file
            String fileName:Path to file
            File file:A file
        FileReader Function of construction method:
            1.Create a FileReader object
            2.Will point the FileReader object to the file to be read
    To use the character input stream:
        1.Create FileReader object, bind data source to be read in construction method
        2.Read the file using the method read in the FileReader object
        3.Release resources
 */
public class Demo02Reader {
    public static void main(String[] args) throws IOException {
        //1. Create FileReader object, bind data source to be read in construction method
        FileReader fr = new FileReader("09_IOAndProperties\\c.txt");
        //2. Use the method read in 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 more than one character at a time, and reads the character into the array.
        char[] cs = new char[1024];//Store multiple characters read
        int len = 0;//The number of valid characters per read is recorded
        while((len = fr.read(cs))!=-1){
            /*
                String Construction method of class
                String(char[] value) Convert character array to string
                String(char[] value, int offset, int count) The number of start index count conversions that convert a part of a character array to a string offset array
             */
            System.out.println(new String(cs,0,len));
        }

        //3. Release resources
        fr.close();
    }
}

17_ Character output stream_ Writer class & introduction to filewriter class

18_ Basic use of character output stream_ Write a single character to a file

import java.io.FileWriter;
import java.io.IOException;

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

    Common member 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, the start index of the off string, and the number of characters written by len.
        - void flush()Flushes the buffer for 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) Constructs a FileWriter object based on the given filename.
        Parameters: destination to write data to
            String fileName:Path to file
            File file:It's a file
        Function of construction method:
            1.A FileWriter object will be created
            2.Creates a file based on the path of the file / file passed in the construction method
            3.Will point the FileWriter object to the created file

    Steps to use character output stream (key points):
        1.Create the FileWriter object and bind the destination to write data in the construction method
        2.write the data to the memory buffer using the method in FileWriter (the process of character conversion to byte)
        3.Use the method flush in FileWriter to refresh the data in the memory buffer to the file
        4.Free resources (data in memory buffer will be flushed to file first)
 */
public class Demo01Writer {
    public static void main(String[] args) throws IOException {
        //1. Create a FileWriter object and bind the destination of the data to be written in the construction method
        FileWriter fw = new FileWriter("09_IOAndProperties\\d.txt");
        //2. Use the method write in FileWriter to write the data to the memory buffer (the process of character conversion to byte)
        //void write(int c) writes a single character.
        fw.write(97);
        //3. Use the method flush in FileWriter to refresh the data in the memory buffer to the file
        //fw.flush();
        //4. Release resources (the data in the memory buffer will be flushed to the file first)
        fw.close();
    }
}

19_ The difference between flush method and close method

import java.io.FileWriter;
import java.io.IOException;

/*
    flush Difference between method and close method
        - flush : Flushes the buffer so that the stream object can continue to be used.
        - close:  First flush the buffer, and then notify the system to release the resources. The stream object can no longer be used.
 */
public class Demo02CloseAndFlush {
    public static void main(String[] args) throws IOException {
        //1. Create a FileWriter object and bind the destination of the data to be written in the construction method
        FileWriter fw = new FileWriter("09_IOAndProperties\\e.txt");
        //2. Use the method write in FileWriter to write the data to the memory buffer (the process of character conversion to byte)
        //void write(int c) writes a single character.
        fw.write(97);
        //3. Use the method flush in FileWriter to refresh the data in the memory buffer to the file
        fw.flush();
        //After refresh, the stream can continue to use
        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 disappeared from memory, so the stream can no longer be used
        fw.write(99);//IOException: Stream closed
    }
}

20_ Other methods of character output stream writing data

import java.io.FileWriter;
import java.io.IOException;

/*
    Other methods of character output stream writing data
        - 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, the start index of the off string, and the number of characters written by len.
 */
public class Demo03Writer {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("09_IOAndProperties\\f.txt");
        char[] cs = {'a','b','c','d','e'};
        //void write(char[] cbuf) writes a 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("legend");

        //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("I'm a programmer",2,3);

        fw.close();
    }
}

21_ Continuation and newline of character output stream

import java.io.FileWriter;
import java.io.IOException;

/*
    Continuation and line feed
    Continue write, append write: construction method with two parameters
        FileWriter(String fileName, boolean append)
        FileWriter(File file, boolean append)
        Parameters:
            String fileName,File file:Destination to write data to
            boolean append:true: no new file will be created to overwrite the source file. You can continue writing; false: create a new file to overwrite the source file
     Wrap: wrap symbol
        windows:\r\n
        linux:/n
        mac:/r
 */
public class Demo04Writer {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("09_IOAndProperties\\g.txt",true);
        for (int i = 0; i <10 ; i++) {
            fw.write("HelloWorld"+i+"\r\n");
        }

        fw.close();
    }
}

22_ Use try_catch_finally handle exceptions in the flow

import java.io.FileWriter;
import java.io.IOException;

/*
    Use try catch finally to handle exceptions in the flow before jdk1.7
    Format:
        try{
            Abnormal code may be generated
        }catch(Exception class variable name){
            Exception handling logic
        }finally{
            Code to be specified
            Resource release
        }
 */
public class Demo01TryCatch {
    public static void main(String[] args) {
        //Improve the scope of variable fw so that finally can use
        //When a variable is defined, it can have no value, but it must have value when it is used
        //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("w:\\09_IOAndProperties\\g.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 {
            //Code to be specified
            //Failed to create the object. fw's default value is null. Null cannot call methods. NullPointerException will be thrown. A judgment needs to be added instead of null releasing resources
            if(fw!=null){
                try {
                    //fw.close The method declaration throws the IOException exception exception object, so we have to deal with the exception object, either throws or try catch
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

23_ Exception handling in JDK7 and JDK9 streams

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

/*
    JDK7 New features of
    After the try, you can add a () to define the flow object in parentheses
    Then the scope of this flow object is valid in try
    try After the code in is executed, the stream 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
        }
 */
public class Demo02JDK7 {
    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("c:\\1.jpg");
            //2. Create a byte output stream object and bind the destination to be written in the construction method
            FileOutputStream fos = new FileOutputStream("d:\\1.jpg");){

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

        }catch (IOException e){
            //Exception handling logic
            System.out.println(e);
        }


    }
}

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

/*
    JDK9 New features
    try The front edge of defines the flow object
    The name of the flow object (variable name) can be introduced directly in () 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 Demo03JDK9 {
    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("c:\\1.jpg");
        //2. Create a byte output stream object and bind the destination to be written in the construction method
        FileOutputStream fos = new FileOutputStream("d:\\1.jpg");

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

        //fos.write(1);//Stream Closed

    }
}

24_ Use the Properties collection to store data and traverse to retrieve the data in the Properties collection

25_ Method store in properties collection

26_ Method load in properties collection

import java.io.FileOutputStream;
import java.io.FileReader;
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 Set is the only set that combines IO flow
        You can use the method store in the Properties collection to persistently write the temporary data in the collection to the hard disk for storage
        You can use the method load in the Properties collection to read the files (key value pairs) saved in the hard disk to the collection for use

    Each key and its corresponding value in the property list is a string.
        Properties Set is a two column set, key and value are strings by default
 */
public class Demo01Properties {
    public static void main(String[] args) throws IOException {
        show03();
    }

    /*
        You can use the method load in the Properties collection to read the files (key value pairs) saved in the hard disk to 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 method load 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 where key value pairs are stored, the default connection symbol between key and value can use =, space (other symbols)
            2.In the file where the key value pair is stored, you can use ා to comment, and the annotated key value pair will not be read again
            3.In the file where the key value pair is stored, both the key and the value are strings by default, without quotation marks
     */
    private static void show03() throws IOException {
        //1. Create the Properties collection object
        Properties prop = new Properties();
        //2. Use the method load in the Properties collection object to read the file where the key value pair is saved
        prop.load(new FileReader("09_IOAndProperties\\prop.txt"));
        //prop.load(new FileInputStream("09_IOAndProperties\\prop.txt"));
        //3. Traverse the Properties set
        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 write the temporary data in the collection to the hard disk for persistence
        void store(OutputStream out, String comments)
        void store(Writer writer, String comments)
        Parameters:
            OutputStream out:Byte output stream, unable to write to Chinese
            Writer writer:Character output stream, can write Chinese
            String comments:Comment, used to explain what the saved file is for
                    Can't use Chinese, will produce garbled code, the default is Unicode encoding
                    "Empty string is generally used"

        Use steps:
            1.Create 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 write the temporary data in the collection to the hard disk for persistence
            4.Release resources
     */
    private static void show02() throws IOException {
        //1. Create 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 a byte output stream / character output stream object and bind the destination to be output in the construction method
        //FileWriter fw = new FileWriter("09_IOAndProperties\\prop.txt");

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

        //Use stringPropertyNames to take out the key in the Properties collection and store it 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) {
            //Get value through key using getProperty method
            String value = prop.getProperty(key);
            System.out.println(key+"="+value);
        }
    }
}

Keywords: Java jvm ascii Windows

Added by jiggaman15dg on Sun, 14 Jun 2020 07:51:46 +0300