How to read the txt file data into arraylist

放肆的年华 提交于 2019-12-30 07:34:09

问题


This following data is inside the Admin.txt file

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

AD001|admin|admin|admin|admin@gmail.com|0123456789|931245678976
AD002|jeff|jeff|jefferyleo|jefferyleo@gmail.com|12345678790|941457431246

how should I read these data into an arraylist??

List<Admin> adminList = new ArrayList<Admin>();

This is the arrayList that I decalred.

BufferedReader br = new BufferedReader(new FileReader("Admin.txt"));
String strLine;
while((strLine = br.readLine()) != null)
{
     String[] values = strLine.split("|");
     adminList.add(new Admin());
}

回答1:


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();
}



回答2:


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));


来源:https://stackoverflow.com/questions/21288895/how-to-read-the-txt-file-data-into-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!