我一直在尝试从 .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
?