Integer.parseInt() throws NumberFormatException for some numbers read using BufferedReader from one file but not another

85 Views Asked by At

I am trying to read numbers from a text file.

The first lines of metro.txt contain:

376 933
0000 Abbesses
0001 Alexandre Dumas

Whereas the first few lines of testnum.txt contain:

444 555
6666 flowers
8888 pumpkin patch

This is my code:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class test {
    public static void main(String[] args) {
        try {
            FileReader input = new FileReader("metro.txt");
            BufferedReader reader = new BufferedReader(input);

            String raw_line = reader.readLine();
            String[] split_line = raw_line.split(" ", 2);

            int num_vertices = Integer.parseInt(split_line[0]);
            int num_edges = Integer.parseInt(split_line[1]);

        } catch (FileNotFoundException ex) { // catch filereader
            System.out.println(ex);
        } catch (IOException ex) { // catch bufferedreader
            System.out.println(ex);
        }
    }
}

When I run it with "metro.txt" in the filereader arg, I get the error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "376"
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
        at java.base/java.lang.Integer.parseInt(Integer.java:668)
        at java.base/java.lang.Integer.parseInt(Integer.java:786)
        at test.main(test.java:15)

Whereas when I run it with "testnum.txt" I get no such error. I was provided "metro.txt" as part of an assignment and created "testnum.txt" myself and can only think of some sort of encoding of the text is causing this.

I think its something to do with how the bufferedreader is reading from "metro.txt" as when I try and compare split_line[0] with an identical string "376" it returns false but I have no idea how to get to the root of this issue.

1

There are 1 best solutions below

0
Oleg Cherednik On

You can use Scanner with define required charset.

public static void main(String... args) throws IOException {
    try (Scanner scan = new Scanner(Path.of("metro.txt"), StandardCharsets.UTF_8)) {
        scan.useLocale(Locale.US);

        int m = scan.nextInt();         // 376
        int n = scan.nextInt();         // 933

        String a1 = scan.next();        // 0000
        String a2 = scan.nextLine();    // Abbesses
        String b1 = scan.next();        // 0001
        String b2 = scan.nextLine();    // Alexandre Dumas
    }
}