我在从文件中读取特定对象并将其保存到ArrayList时遇到问题。
首先,我使用writeCustomer()
编写一个客户。然后我从List customerList
写下所有记录并将它们保存到文件中。这很有效。
然后我想读取保存的文件,所以我使用readCustomer()
读了一行。此方法返回一个Customer
,然后我想使用Clients
返回包含所有readData()
的列表并读取它,行list.add中有nullPointerException(readCustomer(bufferedReader)); < / p>
我的Class Customer
有一个构造函数,并且有一个覆盖方法toString()
。
public class SaveCustomers {
public static void main(String[] args) throws IOException {
List<Customers> customersList = new ArrayList<>();
customersList.add(new Customers("ABC", 10));
customersList.add(new Customers("SGS", 20));
customersList.add(new Customers("FSD", 30));
try (PrintWriter out = new PrintWriter("customer.txt", "UTF-8"))
{ writeData(customersList, out); }
BufferedReader bufferedReader = new BufferedReader(new FileReader("customer.txt"));
List<Customers> newList = readData(bufferedReader);
for(Customers c: newList){
System.out.println(c);
}
}
private static void writeCustomer(PrintWriter out, Customers customers){
out.println(customers.getName()+"|"+customers.getTarrif());
}
private static void writeData(List<Customers> customersList, PrintWriter out){
for(Customers c:customersList){
writeCustomer(out, c);
}
}
public static Customers readCustomer(BufferedReader bufferedReader) throws IOException {
String line = bufferedReader.readLine();
String [] tokens = line.split("\\|");
String name = tokens[0];
int time = Integer.valueOf(tokens[1]);
return new Customers(name, time);
}
public static List<Customers> readData(BufferedReader bufferedReader) throws IOException {
List<Customers> list = new ArrayList<>();
while (bufferedReader.readLine() != null) {
list.add(readCustomer(bufferedReader));
}
return list;
}}
答案 0 :(得分:0)
您接近解决方案;)
方法:
readData(BufferedReader bufferedReader)
只需更改此行
即可for(Customers l : list) {
到这一个:
while (bufferedReader.ready()) {