5

Why an actual number string read from a text can't be parsed with method Integer.valueOf() in java?

Exception :

Exception in thread "main" java.lang.NumberFormatException: For input string: "11127"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.valueOf(Integer.java:766)
    at sharingBike.ReadTxt.readRecord(ReadTxt.java:91)
    at sharingBike.ReadTxt.main(ReadTxt.java:17)

This is my code

        File fileView = new File(filePath);

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileView), "UTF-8"));

        String line;

        int count = 0;
        while ((line = in.readLine()) != null) {
            String[] lins = line.split(";");

            int value;
            value = Integer.valueOf(lins[0]);}
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
林文烨
  • 53
  • 5
  • `valueOf` returns an object of type `Integer`, not a primitive. Use `parseInt` instead. – oyvindhauge Nov 08 '17 at 13:15
  • 1
    your code should work, the only option i can imagine is that you have trailing spaces in that string/integer value that you are trying to parse... – ΦXocę 웃 Пepeúpa ツ Nov 08 '17 at 13:16
  • @ØyvindHauge: `public static int parseInt(String s)` ? – Stefan Nov 08 '17 at 13:16
  • 1
    I assume some non-printable bytes inside the string. Please output them as `System.out.println(Arrays.toString(lins[0].getBytes(UTF_8)))` just to see what you have here. See @assylias answer for a possible example. – Seelenvirtuose Nov 08 '17 at 13:19
  • 1
    @Seelenvirtuose I used the exact string posted in the question (but the BOM bit got lost with the edit of @AndrewTobilko). – assylias Nov 08 '17 at 13:20
  • @assylias Weird. I now also see the BOM (copy-paste into NP++ with hex editor). Very good finding! – Seelenvirtuose Nov 08 '17 at 13:24
  • @Seelenvirtuose Tried to rollback but apparently it's not possible to keep the original string and have the exception formatted... – assylias Nov 08 '17 at 13:25

1 Answers1

12

Here is the content of your string:

System.out.println(Arrays.toString("11127".getBytes()));

which outputs:

[-17, -69, -65, 49, 49, 49, 50, 55]

The first three bytes are a UTF-8 BOM.

You can fix it by removing non-digits from the string first (and use parseInt to return an int instead of an Integer):

int value = Integer.parseInt(lins[0].replaceAll("\\D", "");
assylias
  • 321,522
  • 82
  • 660
  • 783