我一直在尝试一段时间从.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
?
那么,你叫br.readLine()两次 – Clark