0

我一直在尝试从 .txt 文件中读取单个字符串,将其转换为整数,添加新值并将其再次保存到 .txt 文件中。

如果我只写“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

4

2 回答 2

8

从文件中读取最后一行后,br.readLine()将返回 null,然后将其传递给parseInt().
你无法解析null

于 2013-10-08T13:39:24.753 回答
1

尝试交换:

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

这将解决行可能为空的问题。

于 2013-10-08T13:42:14.787 回答