Search code examples
javastringbufferedreadertext-parsing

String to int with BufferedReader


I have this code but when I try to run it I got this error Exception in thread "main" java.lang.NumberFormatException: For input string: "1" Every line is contains a number a name an email and a date so the first character in every line is the number. The tomb[0] is just a number

List<Szemely> lista = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(this.szemelyekcsv))) {
            String line;

            while ((line = br.readLine()) != null) {
                String[] tomb;
                tomb = line.split(";");

               int sor = Integer.parseInt(tomb [0]);
                DateTimeFormatter sima = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDate szul = LocalDate.parse(tomb[3], sima);


                lista.add(new Szemely(sor, tomb[1], tomb[2], szul));

            }
        } catch (FileNotFoundException ex) {
            System.out.println("Nem tudom megnyitni a 'be.txt' fájlt.");
        } catch (IOException ex) {
            System.out.println("Hiba a 'be.txt' fájl olvasása közben.");
        }

when the program reach this line

int sor = Integer.parseInt(tomb [0]);

automaticly jump back to

try (BufferedReader br = new BufferedReader(new FileReader(this.szemelyekcsv))) 

and error... thanks all help.


Solution

  • As pooyan, AxelH and VGR pointed out the problem was indeed one or more invisible characters (e.g. control characters).

    One way to solve this is cut away everything that's not a digit using regular expressions:

    int sor = Integer.parseInt(tomb[0].replaceAll("[^0-9]+", ""));
    

    [^...] = not those characters

    [0-9] = digits

    + = one or more times