以下数据位于Admin.txt文件
中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
我应该如何将这些数据读入arraylist?
List<Admin> adminList = new ArrayList<Admin>();
这是我打算的arrayList。
BufferedReader br = new BufferedReader(new FileReader("Admin.txt"));
String strLine;
while((strLine = br.readLine()) != null)
{
String[] values = strLine.split("|");
adminList.add(new Admin());
}
答案 0 :(得分:1)
像这样添加一个构造函数到Admin
类,但是包含所有数据的字段:
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];
}
}
请注意,这不是您的整个Admin
类,您只需要将构造函数修改为类似于此处的构造函数。
然后在你的循环中改为:
adminList.add(new Admin(values));
答案 1 :(得分:1)
也许这段代码可以帮到你
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();
}