Error Integer.parseInt while reading from txt.txt file. In the file line: "2 4 6". Throws an error: java.lang.NumberFormatException: For input string: "2"

import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; public class Solution { public static void main(String[] args) { ArrayList<Integer> intList = new ArrayList<>(); try { FileReader fr = new FileReader("c:/txt.txt"); Scanner sc = new Scanner(fr); while (sc.hasNext()) { String[] parts = sc.nextLine().split(" "); for (String str : parts) intList.add(Integer.parseInt(str)); } fr.close(); for (Integer i : intList) System.out.println(i); } catch (Exception e) { System.out.println(e); } } } 
  • attach stacktrace - Artem Konovalov
  • maybe something non-printable wedged in. try Integer.parseInt(str.replaceAll("[^\\p{Print}]", "")) - Serodv

1 answer 1

fileReader.readLine () reads the entire line at once. If the file looks like this

  1 2 3 4 12 34 3 4 5 34 23 23 

Then readLine () will give you back 1 2 3 4 12 34

Therefore, after reading, you need to divide the characters into spaces.

 while (fileReader.ready()){ for (String number : fileReader.readLine().split(" ")){ int i = Integer.parseInt(number); if (i % 2 == 0) list.add(i); } } 
  • and still the same Exception in thread "main" java.lang.NumberFormatException: For input string: "12" - Yan S
  • Could you attach the contents of the file to the body of the question by clicking on edit ? - Senior Pomidor
  • made changes to the body - Yan S
  • and the error is exactly the same java.lang.NumberFormatException: For input string: "12" ? Attach a moderated file to your body, please - Senior Pomidor
  • @YanS number 12 - is it the last (or only) in the line? - newman