简体   繁体   English

读取和处理Java中的文本文件

[英]Reading and Manipulating a Text File in Java

I've been trying for a while now to read a single String from a .txt file, convert it to an Integer, add a new value and save it to the .txt file again. 我已经尝试了一段时间,以从.txt文件中读取单个String,将其转换为Integer,添加新值,然后再次将其保存到.txt文件中。

I have been semi successful if I only write "fw.write(String.valueOf(amount));" 如果我只写“ fw.write(String.valueOf(amount));”,我将获得半成功。 to the file, but it just replaces the current String with a new value. 到文件,但是它只是将当前String替换为新值。 I want to grab the current String in the file, convert it to an Integer and add more to the value. 我想获取文件中的当前String,将其转换为Integer,然后将更多值添加到该值。

I currently get a java.lang.NumberFormatException: null error, but I am converting to an Integer so I don't understand. 我目前收到java.lang.NumberFormatException: null错误,但是我要转换为Integer,所以我不明白。 The error points to 错误指向

content = Integer.parseInt(line);

//and

int tax = loadTax() + amount;

Here are my two methods 这是我的两种方法

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;
    }

Can anyone see why it is returning null and not adding tax + amount ? 谁能看到它为什么返回null而不加tax + amount

After you read the last line from the file, br.readLine() will return null, which you then pass to parseInt() . 从文件中读取最后一行后, br.readLine()将返回null,然后将其传递给parseInt()
You can't parse null . 您不能解析null

Try swapping around: 尝试交换:

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

This will fix the issue where line might be null. 这将解决行可能为空的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM