io practice cases

3 practice cases

3.1 assemble to file [ application ]

  • Case requirements
    Read the data in the text file into the collection and traverse the collection. Requirement: each line of data in the file is a collection element

  • Implementation steps

    • Create character buffered input stream object
    • Create an ArrayList collection object
    • Call the method of character buffer input stream object to read data
    • Store the read string data in the collection
    • Release resources
    • Traversal set
  • code implementation

    public class TxtToArrayListDemo {
        public static void main(String[] args) throws IOException {
            //Create character buffered input stream object
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\array.txt"));
    
            //Create an ArrayList collection object
            ArrayList<String> array = new ArrayList<String>();
    
            //Call the method of character buffer input stream object to read data
            String line;
            while ((line=br.readLine())!=null) {
                //Store the read string data in the collection
                array.add(line);
            }
            //Release resources
            br.close();
            //Traversal 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 is used as a line of data in the file

  • Implementation steps

    • Create an ArrayList collection
    • Storing string elements into a collection
    • Create character buffered output stream object
    • Traverse the collection to get each string data
    • Call the method of character buffered output stream object to write data
    • Release 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 into a collection
            array.add("hello");
            array.add("world");
            array.add("java");
    
            //Create character buffered output stream object
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\array.txt"));
    
            //Traverse the collection 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();
            }
    
            //Release resources
            bw.close();
        }
    }
    

3.3 roll call device [ application ]

  • Case requirements
    I have a file that stores the names of the students in the class. Each name occupies one line. It is required to realize the random naming device through the program

  • Implementation steps

    • Create character buffered input stream object
    • Create an ArrayList collection object
    • Call the method of character buffered input stream object to read data
    • Store the read string data in the collection
    • Release resources
    • Use Random to generate a Random number. The range of Random numbers is: [0, the length of the set)
    • Use the random number generated in step 6 as an index to get the value in the ArrayList set
    • Output the data obtained in step 7 to the console
  • code implementation
    public class CallNameDemo {
    public static void main(String[] args) throws IOException {
    //Create character buffered input stream object
    BufferedReader br = new BufferedReader(new FileReader("myCharStream\names.txt"));

            //Create an ArrayList collection object
            ArrayList<String> array = new ArrayList<String>();
    
            //Call the method of character buffered input stream object to read data
            String line;
            while ((line=br.readLine())!=null) {
                //Store the read string data in the collection
                array.add(line);
            }
    
            //Release resources
            br.close();
    
            //Use Random to generate a Random number. The range of Random number is: [0, the length of the set)
            Random r = new Random();
            int index = r.nextInt(array.size());
    
            //Use the random number generated in step 6 as an index to get the value in the ArrayList set
            String name = array.get(index);
    
            //Output the data obtained in step 7 to the console
            System.out.println("The lucky ones are:" + name);
        }
    }
    

3.4 collection to document improved version [ application ]

  • Case requirements
    Write the student data in the ArrayList collection to a text file. Requirements: the data of each student object is used as a line of data in the file
    Format: student number, name, age, residence example: itheima001, Lin Qingxia, 30, Xi'an
  • Implementation steps
    • Define student classes
    • Create an ArrayList collection
    • Create student object
    • Add student object to collection
    • Create character buffered output stream object
    • Traverse the collection to get each student object
    • Splice the data of the student object into a string in the specified format
    • Call the method of character buffered output stream object to write data
    • Release resources
  • code implementation
    • Student class

      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>();
      
              //Create student object
              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");
      
              //Add student object to collection
              array.add(s1);
              array.add(s2);
              array.add(s3);
      
              //Create character buffered output stream object
              BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\students.txt"));
      
              //Traverse the collection to get each student object
              for (Student s : array) {
                  //Splice the data of the student object into a string in the specified format
                  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 buffered output stream object to write data
                  bw.write(sb.toString());
                  bw.newLine();
                  bw.flush();
              }
      
              //Release resources
              bw.close();
          }
      }
      

3.5 document collection improved version [ application ]

  • Case requirements
    Read the data in the text file into the collection and traverse the collection. Requirements: each line of data in the file is the member variable value of a student object
    Example: itheima001, Lin Qingxia, 30, Xi'an
  • Implementation steps
    • Define student classes
    • Create character buffered input stream object
    • Create an ArrayList collection object
    • Call the method of character buffered input stream object to read data
    • Split the read string data with split() to get a string array
    • Create student object
    • Take out each element in the string array and assign the corresponding value to the member variable value of the student object
    • Add student object to collection
    • Release resources
    • Traversal set
  • code implementation
    • Student class
      ditto

    • Test class

      public class FileToArrayListDemo {
          public static void main(String[] args) throws IOException {
              //Create character buffered input stream object
              BufferedReader br = new BufferedReader(new FileReader("myCharStream\\students.txt"));
      
              //Create an ArrayList collection object
              ArrayList<Student> array = new ArrayList<Student>();
      
              //Call the method of character buffered input stream object to read data
              String line;
              while ((line = br.readLine()) != null) {
                  //Split the read string data with split() to get a string array
                  String[] strArray = line.split(",");
      
                  //Create student object
                  Student s = new Student();
                  //Take out each element in the string array and assign the corresponding value to the member variable value of the student object
                  //itheima001, Lin Qingxia, 30, Xi'an
                  s.setSid(strArray[0]);
                  s.setName(strArray[1]);
                  s.setAge(Integer.parseInt(strArray[2]));
                  s.setAddress(strArray[3]);
      
                  //Add student object to collection
                  array.add(s);
              }
      
              //Release resources
              br.close();
      
              //Traversal set
              for (Student s : array) {
                  System.out.println(s.getSid() + "," + s.getName() + "," + s.getAge() + "," + s.getAddress());
              }
          }
      }
      

Keywords: Java

Added by Albright on Wed, 19 Jan 2022 19:47:16 +0200