2014-03-28 68 views
0

我的當前程序從一個文件中讀取,將這些數據添加到客戶對象,然後將該數據添加到列表中。還有第二個文件,我希望閱讀,也將數據添加到我的客戶對象。顧客評分文件,但不是所有顧客都有評分。這是我迄今爲止所做的:如何在Java中讀取併合並兩個文件?

public void readFromFile() 
{ 
    try 
    { 
     BufferedReader inF = new BufferedReader(new FileReader("Customers.txt")); 
     BufferedReader inFR = new BufferedReader(new FileReader("Ratings.txt")); 

     String s = inF.readLine(); 
     String s2 = inFR.readLine(); 
     while(s != null) 
     { 
      String z[] = s.split(","); 
      String y[] = s2.split(" ");  
      Customer c = new Customer(z[0], z[1], z[2], Integer.parseInt(z[3]),z[4]); 
      if(c.getCustomerNr().equals(y[0])) 
      { 
       c.setRating(Integer.parseInt(y[1])); 
      } 
      else 
      { 
       c.setRating(0); 
      } 
      myList.add(c); 
      s = inF.readLine(); 
      s2 = inFR.readLine(); 
     } 

    } 
    catch (FileNotFoundException ex) 
    { 
     System.out.println("File does not exsit."); 
     System.exit(0); 
    } 
    catch (IOException ex) 
    { 
     System.out.println("Could not find line"); 
     System.exit(0); 
    } 
} 

但是,我不斷收到錯誤「空指針異常」在我的拆分方法爲s2。我不確定我做錯了什麼。如果有人能夠給我一個暗示我需要去的地方,那我也會很棒,因爲我喜歡盡我所能去嘗試和解決問題。但是,如果您提供答案,我也會很高興。

感謝

回答

1

你的代碼假設相同數量的文件中的行的,而顯然"Ratings.txt"具有較少的線路。

我的建議是在單獨的循環中處理文件。閱讀評級文件時,請使用正確的客戶號碼搜索客戶的客戶名單。

+0

好的,謝謝你,我現在要試一試:) – entropy