我從讀取文件中的特定對象並將其保存到ArrayList時遇到問題。從文件中讀取對象並將其保存到ArrayList中
首先我使用writeCustomer()
寫一個客戶。然後我從List customerList
寫入所有記錄並將它們保存到文件中。這很好。
然後我想讀取保存的文件,所以我讀了一行使用readCustomer()
。這個方法返回一個Customer
,然後我想用readData()
返回一個包含全部Clients
的列表並讀取它,我在list.add(readCustomer(bufferedReader))行中有nullPointerException;
我的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;
}}
「*我有一個問題....它不起作用*」 - 究竟發生了什麼?例外?錯誤的輸出?無限循環? –
謝謝Sasha降低我的聲譽。我希望,謝謝你做到了,你有更好的心情.... – bartek1982
我沒有downvote,如果你有興趣。評論有時只是一條評論。大多數downvote的人根本沒有評論。 –