[Yugong series] January 2022 Java Teaching Course 55 - reading and writing characters

Article catalog

1, Character reading and writing

1. Why does character stream appear

  • Introduction to character stream Because byte stream is not particularly convenient to operate Chinese, Java provides character stream Character stream = byte stream + encoding table
  • Chinese byte storage When copying a text file with byte stream, the text file will also have Chinese, but there is no problem. The reason is that the bottom operation will automatically splice bytes into Chinese. How to identify Chinese? When storing Chinese characters, the first byte is negative no matter which encoding is selected for storage

2. Coding table

  • What is a character set It is a collection of all characters supported by the system, including national characters, punctuation marks, graphic symbols, numbers, etc l if the computer wants to accurately store and recognize various character set symbols, it needs character coding. A set of character set must have at least one set of character coding. Common character sets include ASCII character set, GBXXX character set, Unicode character set, etc
  • Common character sets
    • ASCII character set: ASCII: it is a set of computer coding system based on Latin alphabet, which is used to display modern English, mainly including control characters (enter key, backspace, line feed key, etc.) and displayable characters (English uppercase and lowercase characters, Arabic numerals and Western symbols) The basic ASCII character set, using 7 bits to represent a character, a total of 128 characters. The ASCII extended character set uses 8 bits to represent a character, a total of 256 characters, which is convenient to support common European characters. It is a collection of all characters supported by the system, including national characters, punctuation marks, graphic symbols, numbers, etc
    • GBXXX character set: GBK: the most commonly used Chinese code table. It is an extended specification based on GB2312 standard. It uses a double byte coding scheme, contains 21003 Chinese characters, is fully compatible with GB2312 standard, and supports traditional Chinese characters, Japanese and Korean characters
    • Unicode character set: UTF-8 encoding: it can be used to represent any character in Unicode standard. It is the preferred encoding in e-mail, web pages and other applications for storing or transmitting text. The Internet Engineering Task Force (IETF) requires that all Internet protocols must support UTF-8 coding. It uses one to four bytes to encode each character Coding rules: 128 US-ASCII characters, only one byte encoding is required Latin and other characters require two byte encoding Most common words (including Chinese) are encoded in three bytes Other rarely used Unicode auxiliary characters use four byte encoding

3. Encoding and decoding problems in strings

  • correlation method
  • Code demonstration
public class StringDemo {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //Define a string
        String s = "China";

        //byte[] bys = s.getBytes(); //[-28, -72, -83, -27, -101, -67]
        //byte[] bys = s.getBytes("UTF-8"); //[-28, -72, -83, -27, -101, -67]
        byte[] bys = s.getBytes("GBK"); //[-42, -48, -71, -6]
        System.out.println(Arrays.toString(bys));

        //String ss = new String(bys);
        //String ss = new String(bys,"UTF-8");
        String ss = new String(bys,"GBK");
        System.out.println(ss);
    }
}

4. Character stream write data

  • introduce Writer: Abstract parent class used to write character stream FileWriter: a common subclass used to write character streams
  • Construction method
  • Member method
  • Refresh and close methods
  • Code demonstration
public class OutputStreamWriterDemo {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("myCharStream\\a.txt");

        //void write(int c): write a character
//        fw.write(97);
//        fw.write(98);
//        fw.write(99);

        //Void write (char [] cbuf): write a character array
        char[] chs = {'a', 'b', 'c', 'd', 'e'};
//        fw.write(chs);

        //void write(char[] cbuf, int off, int len): writes a part of the character array
//        fw.write(chs, 0, chs.length);
//        fw.write(chs, 1, 3);

        //void write(String str): write a string
//        fw.write("abcde");

        //void write(String str, int off, int len): write a part of a string
//        fw.write("abcde", 0, "abcde".length());
        fw.write("abcde", 1, 3);

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

5. Read data from character stream

  • introduce Reader: Abstract parent class used to read character stream FileReader: common subclass for reading character stream
  • Construction method
  • Member method
  • Code demonstration
public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
   
        FileReader fr = new FileReader("myCharStream\\b.txt");

        //int read(): read data one character at a time
//        int ch;
//        while ((ch=fr.read())!=-1) {
//            System.out.print((char)ch);
//        }

        //int read(char[] cbuf): read one character array data at a time
        char[] chs = new char[1024];
        int len;
        while ((len = fr.read(chs)) != -1) {
            System.out.print(new String(chs, 0, len));
        }

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

6. Character stream user registration case

  • Case requirements The user name and password entered by the keyboard are saved locally for permanent storage
  • Implementation steps
    • Get the user name and password entered by the user
    • Write the user name and password entered by the user to the local file
    • Close flow and release resources
  • code implementation
public class CharStreamDemo8 {
    public static void main(String[] args) throws IOException {
        //Requirement: save the user name and password entered by the keyboard to the local for permanent storage
        //Requirement: the user name is on one line only, and the password is on one line only

        //analysis:
        //1. Realize keyboard entry and enter the user name and password
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter user name");
        String username = sc.next();
        System.out.println("Please enter the password");
        String password = sc.next();

        //2. Write the user name and password to the local file respectively.
        FileWriter fw = new FileWriter("charstream\\a.txt");
        //Write the user name and password to the file
        fw.write(username);
        //Indicates that a carriage return line feed is written out windows \ R \ n MacOS \ r Linux \ n
        fw.write("\r\n");
        fw.write(password);
        //Refresh stream
        fw.flush();
        //3. Close the flow and release resources
        fw.close();
    }
}

7. Character buffer stream

  • Introduction to character buffer stream

BufferedWriter: writes text to the character output stream and buffers characters to provide efficient writing of single characters, arrays and strings. You can specify the buffer size or accept the default size. The default value is large enough for most purposes

The character buffer can be used to specify the character size of the input buffer, or the character buffer can be used to read the characters from the input buffer. The default value is large enough for most purposes

  • Construction method
  • Code demonstration
public class BufferedStreamDemo01 {
    public static void main(String[] args) throws IOException {
        //BufferedWriter(Writer out)
        BufferedWriter bw = new BufferedWriter(new                                                            FileWriter("myCharStream\\bw.txt"));
        bw.write("hello\r\n");
        bw.write("world\r\n");
        bw.close();

        //BufferedReader(Reader in)
        BufferedReader br = new BufferedReader(new                                                           FileReader("myCharStream\\bw.txt"));

        //Read data one character at a time
//        int ch;
//        while ((ch=br.read())!=-1) {
//            System.out.print((char)ch);
//        }

        //Read one character array data at a time
        char[] chs = new char[1024];
        int len;
        while ((len=br.read(chs))!=-1) {
            System.out.print(new String(chs,0,len));
        }

        br.close();
    }
}

8. Special functions of character buffer stream

  • Method introduction

BufferedReader:

Method name

explain

String readLine()

Read a line of text. The result is a string containing the contents of the line, excluding any line termination characters. It is null if the end of the stream has been reached

BufferedReader:

  • Code demonstration
public class BufferedStreamDemo02 {
    public static void main(String[] args) throws IOException {

        //Create character buffered output stream
        BufferedWriter bw = new BufferedWriter(new                                                          FileWriter("myCharStream\\bw.txt"));

        //Write data
        for (int i = 0; i < 10; i++) {
            bw.write("hello" + i);
            //bw.write("\r\n");
            bw.newLine();
            bw.flush();
        }

        //Release resources
        bw.close();

        //Create character buffered input stream
        BufferedReader br = new BufferedReader(new                                                          FileReader("myCharStream\\bw.txt"));

        String line;
        while ((line=br.readLine())!=null) {
            System.out.println(line);
        }

        br.close();
    }
}

9.9 data sorting case in character buffer stream operation file

  • Case requirements Use the character buffer stream to read the data in the file, sort and write it to the local file again
  • Implementation steps
    • Read the data in the file into the program
    • Process the read data
    • Add processed data to the collection
    • Sort the data in the collection
    • Writes the data in the sorted collection to a file
  • code implementation
public class CharStreamDemo14 {
    public static void main(String[] args) throws IOException {
        //Requirements: read the data in the file, sort it and write it to the local file again
        //analysis:
        //1. Read the data in the file.
        BufferedReader br = new BufferedReader(new FileReader("charstream\\sort.txt"));
        //The output stream must not be written here because it will empty the contents of the file
        //BufferedWriter bw = new BufferedWriter(new FileWriter("charstream\\sort.txt"));

        String line = br.readLine();
        System.out.println("The data read is" + line);
        br.close();

        //2. Cut according to the space
        String[] split = line.split(" ");//9 1 2 5 3 10 4 6 7 8
        //3. Change the array of string type into int type
        int [] arr = new int[split.length];
        //Traverse the split array for type conversion.
        for (int i = 0; i < split.length; i++) {
            String smallStr = split[i];
            //Type conversion
            int number = Integer.parseInt(smallStr);
            //Store the converted results into arr
            arr[i] = number;
        }
        //4. Sorting
        Arrays.sort(arr);
        System.out.println(Arrays.toString(arr));

        //5. Write the sorted results back to local 1 2 3 4
        BufferedWriter bw = new BufferedWriter(new FileWriter("charstream\\sort.txt"));
        //Write
        for (int i = 0; i < arr.length; i++) {
            bw.write(arr[i] + " ");
            bw.flush();
        }
        //Release resources
        bw.close();

    }
}

summary

Added by vbracknell on Sat, 15 Jan 2022 10:44:16 +0200