2013-10-08 30 views
0

我一直在嘗試一段時間從.txt文件中讀取單個字符串,將其轉換爲整數,然後添加一個新值並將其保存到.txt文件中。用Java讀取和操作文本文件

我已經半成功,如果我只寫「fw.write(String.valueOf(amount));」到文件,但它只是用一個新值替換當前的字符串。我想抓住文件中的當前字符串,將其轉換爲整數並將更多值添加到該值。

我目前得到java.lang.NumberFormatException: null錯誤,但我轉換爲整數,所以我不明白。錯誤指向

content = Integer.parseInt(line); 

//and 

int tax = loadTax() + amount; 

這裏是我的兩個方法

public void saveTax(int amount) throws NumberFormatException, IOException { 
    int tax = loadTax() + amount; 
    try { 
     File file = new File("data/taxPot.txt"); 
     FileWriter fw = new FileWriter(file.getAbsoluteFile()); 

     fw.write(String.valueOf(tax)); 
     fw.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 



public int loadTax() throws NumberFormatException, IOException { 

     BufferedReader br = new BufferedReader(new FileReader("data/taxPot.txt")); 

     String line = br.readLine(); 
     int content = 0; 

     while (line != null) { 
      line = br.readLine(); 
      content = Integer.parseInt(line); 
     } 
      br.close(); 

      return content; 
    } 

任何人都可以看到爲什麼它返回null,並且不添加tax + amount

+3

那麼,你叫br.readLine()兩次 – Clark

回答

1

試換各地:

if (line == null) 
    return content; 
do { 
    content = Integer.parseInt(line); 
    line = br.readLine(); 
} while (line != null); 

這將解決其中線可能爲空的問題。

+0

感謝大家的評論。這個評論爲我帶來了預期的結果。我知道這很簡單,並且吸取了教訓。謝謝davecom! –

+0

沒問題,@ SLaks幫助我快速查看需要更改的代碼。 – davecom

8

從文件中讀取最後一行後,br.readLine()將返回空值,然後傳遞給parseInt()。你不能解析null

+0

謝謝指出。當你一直盯着那麼久的東西重寫它時,這些小事似乎並不那麼明顯。 –