2016-03-21 221 views
-1

我從讀取文件中的特定對象並將其保存到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; 
}} 
+1

「*我有一個問題....它不起作用*」 - 究竟發生了什麼?例外?錯誤的輸出?無限循環? –

+0

謝謝Sasha降低我的聲譽。我希望,謝謝你做到了,你有更好的心情.... – bartek1982

+0

我沒有downvote,如果你有興趣。評論有時只是一條評論。大多數downvote的人根本沒有評論。 –

回答

0

你是接近的解決方案;)

在方法:

readData(BufferedReader bufferedReader) 

此行

for(Customers l : list) { 

只要改變這一個:

while (bufferedReader.ready()) { 
+0

謝謝你。它工作安靜很好。我的輸出看起來像:BC 10 GS 20 SD 30.但它是開始的東西:) – bartek1982

+0

這很奇怪,bufferedReader.readLine();雖然在customer.txt文件中有ABC | 10,但是返回BC | 10 ... – Ben

+0

Ok while use(bufferedReader.ready()){while while(bufferedReader.read()!= -1){solution ) – Ben

相關問題