简体   繁体   中英

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.

I have been semi successful if I only write "fw.write(String.valueOf(amount));" to the file, but it just replaces the current String with a new value. I want to grab the current String in the file, convert it to an Integer and add more to the value.

I currently get a java.lang.NumberFormatException: null error, but I am converting to an Integer so I don't understand. 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 ?

After you read the last line from the file, br.readLine() will return null, which you then pass to parseInt() .
You can't parse 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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