BOM of Integer.parseInt() doom

Tl;dr; version: Byte order mark in text file was responsible for Integer.parseInt() method throwing an exception (if it wasn’t obvious from a title).

That post is probably first one to talk about some specific issue, so here we go for a ride! In case you missed categories marks — it’s about Java, version 1.8.0_45.

Yesterday I was teaching my girlfriend how to code in Java (let me omit my reasons for choosing this language). It was actually related to second day of Advent of Code (which was described in previous post). assigment. Suddenly I receive complaint from her, that her IDE throws NumberFormatException for her Integer.parseInt() method.

Code responsible for this functionality looked like this:

FileReader fileReader = new FileReader(“input.txt”); Scanner fileScanner = new Scanner(fileReader); while(fileScanner.hasNext()) { String line = fileScanner.next().split(“x”); int length = Integer.parseInt(line[0]); (…) }

FileReader fileReader = new FileReader(“input.txt”);

Scanner fileScanner = new Scanner(fileReader);

while(fileScanner.hasNext())

String line = fileScanner.next().split(“x”);

And content of input.txt file was “2x3x4″. As simple as that. And result was an exception for highlightened line — but shown as ” 3″, instead of simply “3′.

My first thought (along with my friends from college) was that there is some whitespace hidden in this string that we didn’t see. So, first thing to do — add String.trim(). Nope, it doesn’t work. Then while debugging it turned out that this whitespace was added inside the parseInt() method. Frankly, the code was working for my input file from assignment. So the problem wasn’t with code, but with input file.

So I checked file in vim and well.. There was nothing weird with it that could cause such problems. Of course this is the moment to call me a filthy casual that has incorrect vim configuration (we probably all do, but nevermind). Then I changed my approach and used Geany to open it, and saw that option “Save BOM” turned on. I turned it off and suddenly whole code begins to work.


Originally published at www.blog.smyk.it on December 4, 2015.