How to read the txt file data into arraylist

后端 未结 2 1175
自闭症患者
自闭症患者 2021-01-07 07:27

This following data is inside the Admin.txt file

id, username, password, name, email, contactNumber, icNumber

AD001|admin|admin|admin|admin@gmail.com         


        
相关标签:
2条回答
  • 2021-01-07 07:52

    Perhaps this code can help you

    public static void main(String[] args) throws Exception{
    
          BufferedReader br = new BufferedReader(new FileReader("Admin.txt"));
          ArrayList<Admin> al = new ArrayList<Admin>();
          String line = null;
          while ((line = br.readLine()) != null) {
            Admin admin = new Admin();
            String lines[] = line.split("|");
            /*adjust accordingly
            admin.setName(lines[0]);
            admin.setUser(lines[1]);
                ....*/
            al.add(admin);          
          }
          br.close();
    }
    
    0 讨论(0)
  • 2021-01-07 07:55

    Add a constructor to your Admin class like this but with fields for all your data:

    public class Admin {
        private final String id, username, password, name, email, contactNumber, icNumber;
        public Admin (String[] values) {
            this.id = values[0];
            this.username = values[1];
            this.password = values[2];
            this.name = values[3];
            this.email = values[4];
            this.contactNumber = values[5];
            this.icNumber = values[6];
        }
    }
    

    Note that this isn't meant to be your entire Admin class, you only need to modify the constructor to look like the one here.

    Then in your loop do this instead:

    adminList.add(new Admin(values));
    
    0 讨论(0)
提交回复
热议问题