[英]How to read the txt file data into arraylist
以下數據在Admin.txt文件中
ID,用戶名,密碼,名稱,電子郵件,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());
}
像這樣向您的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));
也許這段代碼可以幫助您
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.