Byte Buffer Stream-Character Stream

1. Byte buffer stream

1.1 Byte Buffer Stream Construction Method [Application]

  • Introduction to Byte Buffer Stream

    • lBufferOutputStream: This class implements buffering output streams. By setting such an output stream, the application can write bytes to the underlying output stream without causing calls to the underlying system for each byte written.

    • lBufferedInputStream: Creating BufferedInputStream creates an internal buffer array. When bytes are read or skipped from the stream, the internal buffer will be refilled from the included input stream as needed, many bytes at a time.

  • Construction method:

    Method name Explain
    BufferedOutputStream(OutputStream out) Create byte buffer output stream object
    BufferedInputStream(InputStream in) Create byte buffer input stream objects
  • Sample code

    public class BufferStreamDemo {
        public static void main(String[] args) throws IOException {
            //Byte buffer output stream: Buffered Output Stream (Output Stream out)
     
            BufferedOutputStream bos = new BufferedOutputStream(new 				                                       FileOutputStream("myByteStream\\bos.txt"));
            //Write data
            bos.write("hello\r\n".getBytes());
            bos.write("world\r\n".getBytes());
            //Releasing resources
            bos.close();
        
    
            //Byte buffer input stream: Buffered Input Stream (Input Stream in)
            BufferedInputStream bis = new BufferedInputStream(new                                                          FileInputStream("myByteStream\\bos.txt"));
    
            //Read one byte of data at a time
    //        int by;
    //        while ((by=bis.read())!=-1) {
    //            System.out.print((char)by);
    //        }
    
            //Read one byte array data at a time
            byte[] bys = new byte[1024];
            int len;
            while ((len=bis.read(bys))!=-1) {
                System.out.print(new String(bys,0,len));
            }
    
            //Releasing resources
            bis.close();
        }
    }
    

1.2 Byte Stream Copy Video [Application]

  • Case requirements

    Copy "E: itcast byte stream copy picture. avi" to "byte stream copy picture. avi" in the module directory

  • Implementation steps

    • Creating byte input stream objects from data sources

    • Create byte output stream objects based on destination

    • Read and write data, copy video

    • Releasing resources

  • code implementation

    public class CopyAviDemo {
        public static void main(String[] args) throws IOException {
            //Record start time
            long startTime = System.currentTimeMillis();
    
            //Copy Video
    //        method1();
    //        method2();
    //        method3();
            method4();
    
            //End time of recording
            long endTime = System.currentTimeMillis();
            System.out.println("Time-consuming:" + (endTime - startTime) + "Millisecond");
        }
    
        //Byte buffer stream reads and writes an array of bytes at a time
        public static void method4() throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\Byte Stream Copy Pictures.avi"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\Byte Stream Copy Pictures.avi"));
    
            byte[] bys = new byte[1024];
            int len;
            while ((len=bis.read(bys))!=-1) {
                bos.write(bys,0,len);
            }
    
            bos.close();
            bis.close();
        }
    
        //Byte buffer stream reads and writes one byte at a time
        public static void method3() throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\Byte Stream Copy Pictures.avi"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\Byte Stream Copy Pictures.avi"));
    
            int by;
            while ((by=bis.read())!=-1) {
                bos.write(by);
            }
    
            bos.close();
            bis.close();
        }
    
    
        //Basic byte stream reads and writes an array of bytes at a time
        public static void method2() throws IOException {
            //E: itcast byte stream copy picture. avi
            //Byte stream copy image in module directory. avi
            FileInputStream fis = new FileInputStream("E:\\itcast\\Byte Stream Copy Pictures.avi");
            FileOutputStream fos = new FileOutputStream("myByteStream\\Byte Stream Copy Pictures.avi");
    
            byte[] bys = new byte[1024];
            int len;
            while ((len=fis.read(bys))!=-1) {
                fos.write(bys,0,len);
            }
    
            fos.close();
            fis.close();
        }
    
        //Basic byte stream reads and writes one byte at a time
        public static void method1() throws IOException {
            //E: itcast byte stream copy picture. avi
            //Byte stream copy image in module directory. avi
            FileInputStream fis = new FileInputStream("E:\\itcast\\Byte Stream Copy Pictures.avi");
            FileOutputStream fos = new FileOutputStream("myByteStream\\Byte Stream Copy Pictures.avi");
    
            int by;
            while ((by=fis.read())!=-1) {
                fos.write(by);
            }
    
            fos.close();
            fis.close();
        }
    }
    

2. Character Stream

2.1 Why is there a character stream [Understanding]

  • Introduction to Character Stream

    Since Chinese is not particularly convenient for byte stream operations, Java provides character streams.

    Character stream = byte stream + encoding table

  • Byte Storage in Chinese

    When copying text files with byte streams, the text files will also have Chinese, but no problem. The reason is that the bottom operation will automatically splice bytes into Chinese. How to recognize Chinese?

    When Chinese characters are stored, the first byte is negative no matter which encoding storage is chosen.

2.2 Coding Table [Understanding]

  • What is a character set?

    It is a collection of all characters supported by a system, including national characters, punctuation symbols, graphical symbols, numbers, etc.

    To accurately store and recognize all kinds of character set symbols, a computer needs character encoding. A set of character sets must have at least one set of character encoding. Common character sets include ASCII character set, GBXXX character set, Unicode character set, etc.

  • Common character sets

    • ASCII Character Set:

      lASCII: A computer coding system based on Latin letters for displaying modern English, mainly including control characters (return key, backspace, line break key, etc.) and displayable characters (English upper and lower case characters, Arabic numerals and Western symbols).

      The basic ASCII character set uses seven bits to represent one character, a total of 128 characters. ASCII's extended character set uses 8 bits to represent a character, a total of 256 characters, to facilitate support for commonly used European characters. It is a collection of all characters supported by a system, including national characters, punctuation symbols, graphical 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. It contains 21003 Chinese characters and is fully compatible with GB2312 standard. It also supports traditional Chinese characters, Japanese and Korean Chinese characters, etc.

    • 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 Working Group (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 with only one byte encoding

      Latin and other characters, requiring two byte encoding

      Most commonly used words (including Chinese) are encoded in three bytes.

      Other rarely used Unicode auxiliary characters, using four-byte encoding

Encoding and Decoding in 2.3 Strings [Application]

  • correlation method

    Method name Explain
    byte[] getBytes() Encoding the String into a series of bytes using the platform's default character set
    byte[] getBytes(String charsetName) Encoding the String into a series of bytes using the specified character set
    String(byte[] bytes) Use the platform's default character set to decode the specified byte array to create a string
    String(byte[] bytes, String charsetName) Creates a string by decoding the specified byte array with the specified character set
  • 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);
        }
    }
    

Encoding and Decoding in 2.4 Character Stream [Application]

  • Two Classes Related to Coding and Decoding in Character Stream

    • InputStreamReader: A Bridge from Byte Stream to Character Stream

      It reads bytes and decodes them into characters using the specified encoding

      The character set it uses can be specified by name, explicitly, or acceptance of the platform's default character set.

    • Output Stream Writer: A Bridge from Character Stream to Byte Stream

      A bridge from a character stream to a byte stream, encoding the written characters into bytes using the specified encoding

      The character set it uses can be specified by name, explicitly, or acceptance of the platform's default character set.

  • Construction method

    Method name Explain
    InputStreamReader(InputStream in) Creating InputStreamReader objects with default character encoding
    InputStreamReader(InputStream in,String chatset) Create an InputStreamReader object using the specified character encoding
    OutputStreamWriter(OutputStream out) Creating OutputStreamWriter objects with default character encoding
    OutputStreamWriter(OutputStream out,String charset) Create an OutputStreamWriter object using the specified character encoding
  • Code demonstration

    public class ConversionStreamDemo {
        public static void main(String[] args) throws IOException {
            //OutputStreamWriter osw = new OutputStreamWriter(new                                             FileOutputStream("myCharStream\\osw.txt"));
            OutputStreamWriter osw = new OutputStreamWriter(new                                              FileOutputStream("myCharStream\\osw.txt"),"GBK");
            osw.write("China");
            osw.close();
    
            //InputStreamReader isr = new InputStreamReader(new 	                                         FileInputStream("myCharStream\\osw.txt"));
            InputStreamReader isr = new InputStreamReader(new                                                 FileInputStream("myCharStream\\osw.txt"),"GBK");
            //Read one character data at a time
            int ch;
            while ((ch=isr.read())!=-1) {
                System.out.print((char)ch);
            }
            isr.close();
        }
    }
    

Five Ways of 2.5 Character Streaming Data [Application]

  • Method Introduction

    Method name Explain
    void write(int c) Write a character
    void write(char[] cbuf) Write an array of characters
    void write(char[] cbuf, int off, int len) Write part of the character array
    void write(String str) Write a string
    void write(String str, int off, int len) Write a part of a string
  • Method of refreshing and closing

    Method name Explain
    flush() Refresh the stream and then continue to write data
    close() Close the flow and release resources, but refresh the flow before closing. Once closed, you can't write data anymore.
  • Code demonstration

    public class OutputStreamWriterDemo {
        public static void main(String[] args) throws IOException {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myCharStream\\osw.txt"));
    
            //void write(int c): Write a character
    //        osw.write(97);
    //        osw.write(98);
    //        osw.write(99);
    
            //void writ(char[] cbuf): Writes an array of characters
            char[] chs = {'a', 'b', 'c', 'd', 'e'};
    //        osw.write(chs);
    
            //void write(char[] cbuf, int off, int len): Writes part of the character array
    //        osw.write(chs, 0, chs.length);
    //        osw.write(chs, 1, 3);
    
            //void write(String str): Write a string
    //        osw.write("abcde");
    
            //void write(String str, int off, int len): Write a part of a string
    //        osw.write("abcde", 0, "abcde".length());
            osw.write("abcde", 1, 3);
    
            //Releasing resources
            osw.close();
        }
    }
    

2.6 Character Stream Reading Data in Two Ways [Application]

  • Method Introduction

    Method name Explain
    int read() Read one character data at a time
    int read(char[] cbuf) Read one character array data at a time
  • Code demonstration

    public class InputStreamReaderDemo {
        public static void main(String[] args) throws IOException {
       
            InputStreamReader isr = new InputStreamReader(new FileInputStream("myCharStream\\ConversionStreamDemo.java"));
    
            //int read(): Read one character data at a time
    //        int ch;
    //        while ((ch=isr.read())!=-1) {
    //            System.out.print((char)ch);
    //        }
    
            //int read(char[] cbuf): Read an array of characters at a time
            char[] chs = new char[1024];
            int len;
            while ((len = isr.read(chs)) != -1) {
                System.out.print(new String(chs, 0, len));
            }
    
            //Releasing resources
            isr.close();
        }
    }
    

2.7 Character Stream Copy Java File [Application]

  • Case requirements

    Copy Conversion StreamDemo. Java from the module directory to Copy.java from the module directory

  • Implementation steps

    • Creating character input stream objects from data sources
    • Create character output stream objects based on destination
    • Read and write data, copy files
    • Releasing resources
  • code implementation

    public class CopyJavaDemo01 {
        public static void main(String[] args) throws IOException {
            //Creating character input stream objects from data sources
            InputStreamReader isr = new InputStreamReader(new FileInputStream("myCharStream\\ConversionStreamDemo.java"));
            //Create character output stream objects based on destination
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myCharStream\\Copy.java"));
    
            //Read and write data, copy files
            //Read and write one character data at a time
    //        int ch;
    //        while ((ch=isr.read())!=-1) {
    //            osw.write(ch);
    //        }
    
            //Read and write one character array data at a time
            char[] chs = new char[1024];
            int len;
            while ((len=isr.read(chs))!=-1) {
                osw.write(chs,0,len);
            }
    
            //Releasing resources
            osw.close();
            isr.close();
        }
    }
    

2.8 Character Stream Copy Java File Improvement Edition [Application]

  • Case requirements

    Copy Conversion StreamDemo. Java from the module directory to Copy.java from the module directory using the convenient stream object.

  • Implementation steps

    • Creating character input stream objects from data sources

    • Create character output stream objects based on destination

    • Read and write data, copy files

    • Releasing resources

  • code implementation

    public class CopyJavaDemo02 {
        public static void main(String[] args) throws IOException {
            //Creating character input stream objects from data sources
            FileReader fr = new FileReader("myCharStream\\ConversionStreamDemo.java");
            //Create character output stream objects based on destination
            FileWriter fw = new FileWriter("myCharStream\\Copy.java");
    
            //Read and write data, copy files
    //        int ch;
    //        while ((ch=fr.read())!=-1) {
    //            fw.write(ch);
    //        }
    
            char[] chs = new char[1024];
            int len;
            while ((len=fr.read(chs))!=-1) {
                fw.write(chs,0,len);
            }
    
            //Releasing resources
            fw.close();
            fr.close();
        }
    }
    

2.9 Character Buffer Stream [Application]

  • Introduction to Character Buffer Stream

    • Buffered Writer: Write text to the character output stream, buffering characters to provide efficient writing of individual characters, arrays and strings. Buffer size can be specified, or default size can be accepted. The default value is large enough to be used for most purposes

    • BufferedReader: Read text from the character input stream, buffer characters to provide efficient reading of characters, arrays and rows, specify the buffer size, or use the default size. The default value is large enough to be used for most purposes

  • Construction method

    Method name Explain
    BufferedWriter(Writer out) Create character buffer output stream object
    BufferedReader(Reader in) Create character buffer input stream objects
  • 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 one character data 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();
        }
    }
    

2.10 Character Buffer Stream Copies Java Files [Applications]

  • Case requirements

    Copy ConversionStreamDemo.java from the module directory to Copy.java from the module directory

  • Implementation steps

    • Creating character buffer input stream objects from data sources
    • Create character buffer output stream object based on destination
    • Read and write data, copy files, using the unique function of character buffer stream to achieve
    • Releasing resources
  • code implementation

    public class CopyJavaDemo01 {
        public static void main(String[] args) throws IOException {
            //Creating character buffer input stream objects from data sources
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\ConversionStreamDemo.java"));
            //Create character buffer output stream object based on destination
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\Copy.java"));
    
            //Read and write data, copy files
            //Read and write one character data at a time
    //        int ch;
    //        while ((ch=br.read())!=-1) {
    //            bw.write(ch);
    //        }
    
            //Read and write one character array data at a time
            char[] chs = new char[1024];
            int len;
            while ((len=br.read(chs))!=-1) {
                bw.write(chs,0,len);
            }
    
            //Releasing resources
            bw.close();
            br.close();
        }
    }
    

2.11 Character Buffer Stream Specific Function [Application]

  • Method Introduction

    BufferedWriter:

    Method name Explain
    void newLine() Write a line separator whose string is defined by system attributes

    BufferedReader:

    Method name Explain
    String readLine() Read a line of text. The result is a string containing the contents of a row, excluding any line termination character. If the end of the stream has arrived, it is null.
  • Code demonstration

    public class BufferedStreamDemo02 {
        public static void main(String[] args) throws IOException {
    
            //Create a character buffer 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();
            }
    
            //Releasing resources
            bw.close();
    
            //Create character buffer input stream
            BufferedReader br = new BufferedReader(new                                                          FileReader("myCharStream\\bw.txt"));
    
            String line;
            while ((line=br.readLine())!=null) {
                System.out.println(line);
            }
    
            br.close();
        }
    }
    

2.12 Character Buffer Stream Specific Function Copies Java Files [Applications]

  • Case requirements

    Copy ConversionStreamDemo.java from the module directory to Copy.java from the module directory using unique functions

  • Implementation steps

    • Creating character buffer input stream objects from data sources
    • Create character buffer output stream object based on destination
    • Read and write data, copy files, using the unique function of character buffer stream to achieve
    • Releasing resources
  • code implementation

    public class CopyJavaDemo02 {
        public static void main(String[] args) throws IOException {
            //Creating character buffer input stream objects from data sources
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\ConversionStreamDemo.java"));
            //Create character buffer output stream object based on destination
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\Copy.java"));
    
            //Read and write data, copy files
            //Implementation with Character Buffer Stream Specific Function
            String line;
            while ((line=br.readLine())!=null) {
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
    
            //Releasing resources
            bw.close();
            br.close();
        }
    }
    

2.13IO Flow Summary [Understanding]

  • Byte stream

    [External Link Picture Transfer Failure (img-EMrjdvFN-1565866951509) (img IO Summary Byte Stream. jpg)]

  • Character stream

    [External Link Picture Transfer Failure (img-5xoKJ8S-1565866951510) (imgIO Summary Character Stream. jpg)]

3 Practice Cases

3.1 Collection to Files [Applications]

  • Case requirements

    Read the data from the text file into the collection and traverse the collection. Requirement: Each row of data in the file is a collection element

  • Implementation steps

    • Create character buffer input stream objects
    • Creating ArrayList Collection Objects
    • Calling method of character buffer input stream object to read data
    • Store read string data in a collection
    • Releasing resources
    • Ergodic set
  • code implementation

    public class TxtToArrayListDemo {
        public static void main(String[] args) throws IOException {
            //Create character buffer input stream objects
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\array.txt"));
    
            //Creating ArrayList Collection Objects
            ArrayList<String> array = new ArrayList<String>();
    
            //Calling method of character buffer input stream object to read data
            String line;
            while ((line=br.readLine())!=null) {
                //Store read string data in a collection
                array.add(line);
            }
            //Releasing resources
            br.close();
            //Ergodic set
            for(String s : array) {
                System.out.println(s);
            }
        }
    }
    

3.2 File to Collection [Application]

  • Case requirements

    Write the string data in the ArrayList collection to a text file. Requirement: Each string element acts as a row of data in the file

  • Implementation steps

    • Create an ArrayList collection
    • Storing string elements in a collection
    • Create character buffer output stream object
    • Traverse the set to get each string data
    • Call the method of character buffer output stream object to write data
    • Releasing resources
  • code implementation

    public class ArrayListToTxtDemo {
        public static void main(String[] args) throws IOException {
            //Create an ArrayList collection
            ArrayList<String> array = new ArrayList<String>();
    
            //Storing string elements in a collection
            array.add("hello");
            array.add("world");
            array.add("java");
    
            //Create character buffer output stream object
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\array.txt"));
    
            //Traverse the set to get each string data
            for(String s : array) {
                //Call the method of character buffer output stream object to write data
                bw.write(s);
                bw.newLine();
                bw.flush();
            }
    
            //Releasing resources
            bw.close();
        }
    }
    

3.3 roll caller [application]

  • Case requirements

    I have a file in which the names of classmates are stored. Each name occupies one line. It is required to implement the naming device by program.

  • Implementation steps

    • Create character buffer input stream objects
    • Creating ArrayList Collection Objects
    • Calling method of character buffer input stream object to read data
    • Store read string data in a collection
    • Releasing resources
    • Random is used to generate a random number whose range is: [0, the length of the set]
    • The random number generated in step 6 is indexed into the ArrayList collection to get the value
    • Output the data from Step 7 to the console
  • code implementation

    public class CallNameDemo {
        public static void main(String[] args) throws IOException {
            //Create character buffer input stream objects
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\names.txt"));
    
            //Creating ArrayList Collection Objects
            ArrayList<String> array = new ArrayList<String>();
    
            //Calling method of character buffer input stream object to read data
            String line;
            while ((line=br.readLine())!=null) {
                //Store read string data in a collection
                array.add(line);
            }
    
            //Releasing resources
            br.close();
    
            //Random is used to generate a random number whose range is: [0, the length of the set]
            Random r = new Random();
            int index = r.nextInt(array.size());
    
            //The random number generated in step 6 is indexed into the ArrayList collection to get the value
            String name = array.get(index);
    
            //Output the data from Step 7 to the console
            System.out.println("The lucky ones are:" + name);
        }
    }
    

3.4 Collection to File Improvement Edition [Application]

  • Case requirements

    Write the student data in the ArrayList collection to the text file. Requirements: Each student object's data is a row of data in the file
    Format: Student ID, Name, Age, Place of Residence. Examples: itheima001, Lin Qingxia, 30, Xi'an

  • Implementation steps

    • Defining student classes
    • Create an ArrayList collection
    • Creating Student Objects
    • Adding student objects to collections
    • Create character buffer output stream object
    • Traverse the set to get each student object
    • Stitching data from student objects into strings in specified formats
    • Call the method of character buffer output stream object to write data
    • Releasing resources
  • code implementation

    • Student category

      public class Student {
          private String sid;
          private String name;
          private int age;
          private String address;
      
          public Student() {
          }
      
          public Student(String sid, String name, int age, String address) {
              this.sid = sid;
              this.name = name;
              this.age = age;
              this.address = address;
          }
      
          public String getSid() {
              return sid;
          }
      
          public void setSid(String sid) {
              this.sid = sid;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          public String getAddress() {
              return address;
          }
      
          public void setAddress(String address) {
              this.address = address;
          }
      }
      
    • Test class

      public class ArrayListToFileDemo {
          public static void main(String[] args) throws IOException {
              //Create an ArrayList collection
              ArrayList<Student> array = new ArrayList<Student>();
      
              //Creating Student Objects
              Student s1 = new Student("itheima001", "Lin Qingxia", 30, "Xi'an");
              Student s2 = new Student("itheima002", "Zhang Manyu", 35, "Wuhan");
              Student s3 = new Student("itheima003", "Wang Zuxian", 33, "Zhengzhou");
      
              //Adding student objects to collections
              array.add(s1);
              array.add(s2);
              array.add(s3);
      
              //Create character buffer output stream object
              BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\students.txt"));
      
              //Traverse the set to get each student object
              for (Student s : array) {
                  //Stitching data from student objects into strings in specified formats
                  StringBuilder sb = new StringBuilder();
                  sb.append(s.getSid()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress());
      
                  //Call the method of character buffer output stream object to write data
                  bw.write(sb.toString());
                  bw.newLine();
                  bw.flush();
              }
      
              //Releasing resources
              bw.close();
          }
      }
      

3.5 File to Collection Improvement Edition [Application]

  • Case requirements

    Read the data from the text file into the collection and traverse the collection. Requirements: Each row of data in the file is a member variable value of a student object
    Examples: itheima001, Lin Qingxia, 30, Xi'an

  • Implementation steps

    • Defining student classes
    • Create character buffer input stream objects
    • Creating ArrayList Collection Objects
    • Calling method of character buffer input stream object to read data
    • The read string data is split() to get an array of strings.
    • Creating Student Objects
    • Remove each element of the string array and assign the corresponding value to the member variable value of the student object.
    • Adding student objects to collections
    • Releasing resources
    • Ergodic set
  • code implementation

    • Student category

      Ibid.

    • Test class

      public class FileToArrayListDemo {
          public static void main(String[] args) throws IOException {
              //Create character buffer input stream objects
              BufferedReader br = new BufferedReader(new FileReader("myCharStream\\students.txt"));
      
              //Creating ArrayList Collection Objects
              ArrayList<Student> array = new ArrayList<Student>();
      
              //Calling method of character buffer input stream object to read data
              String line;
              while ((line = br.readLine()) != null) {
                  //The read string data is split() to get an array of strings.
                  String[] strArray = line.split(",");
      
                  //Creating Student Objects
                  Student s = new Student();
                  //Remove each element of the string array and assign the corresponding value to the member variable value of the student object.
                  //Itheima 001, Lin Qingxia, 30, Xi'an
                  s.setSid(strArray[0]);
                  s.setName(strArray[1]);
                  s.setAge(Integer.parseInt(strArray[2]));
                  s.setAddress(strArray[3]);
      
                  //Adding student objects to collections
                  array.add(s);
              }
      
              //Releasing resources
              br.close();
      
              //Ergodic set
              for (Student s : array) {
                  System.out.println(s.getSid() + "," + s.getName() + "," + s.getAge() + "," + s.getAddress());
              }
          }
      }
      

Keywords: Java encoding ascii

Added by jd023 on Thu, 15 Aug 2019 15:40:04 +0300