假设我有一个文本文件 DataBase.txt ,其中包含以下内容:
1 leo messi 12.12.1986
2 cristiano ronaldo 22.01.1985
3 arjen robben 14.11.1991
一个自定义的arraylist,看起来像这样:
public static ArrayList<Rows> InfoList = new ArrayList<Rows>();
这是我使用setter,getters和toString方法的 Rows 类实现:
public class Rows {
public int id;
public String firstName;
public String secondName;
public String dateOfbrth;
@Override
public String toString() {
return this.id + " " + this.firstName + " " +
this.secondName + " " + this.dateOfbrth;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getSecondName() {
return secondName;
}
public String getDateOfbrth() {
return dateOfbrth;
}
public void setId(int id) {
this.id = id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public void setDateOfbrth(String dateOfbrth) {
this.dateOfbrth = dateOfbrth;
}
}
因此。问题是:如何将文本文件内容写入arrayList,其中每个元素都将被引用到类Rows中自己的字段。尽管每条线的空间数不同?哪种算法或Java类对此有用?
我是Java的新手所以我尝试使用 BuffredReader 来做这件事,但我坚持分离 行 并将每个元素添加到< EM>的ArrayList :
try (BufferedReader br = new BufferedReader(new FileReader("F:/DataBase.txt"))) {
for (String line; (line = br.readLine()) != null; ) {
}
}
感谢您的帮助
答案 0 :(得分:2)
这是方式:
try (BufferedReader br = new BufferedReader(new FileReader("F:/DataBase.txt"))) {
String line;
while((line = br.readLine())!=null ) {
String[] values = line.split("\\s+");
...
}
}
答案 1 :(得分:2)
while ((line = br.readLine()) != null) {
String[] row = line.split("\\s+");
Row row = new Row();
row.setId(row[0]);
row.setFirstName(row[1]);
row.setSecondName(row[2]);
row.setDateOfbrth(row[3]);
InfoList.add(row);
}
\ s +是一个正则表达式,它会导致任意数量的连续空格将您的字符串拆分为标记,请参阅此答案How to split a String by space 希望它有所帮助。