Search code examples
javaandroidnumberformatexception

java.lang.NumberFormatException: Invalid int: "5"


I try to read a .txt file which is basically a CSV file which is located in the Assets folder in Android. In the first row there is the number of row and columns of the file The rest is composed by the values, i use a ";" to separate each other.

Here's the code which causes this strange error:

 public static int[][] getMatrix(InputStream stream) throws Exception {

    BufferedReader br = new BufferedReader((new InputStreamReader(stream, "UTF-8")));
    String buffer;
    String[] current;
    int[][] marbles = null;

    //Reading the matrix from file

    if((buffer = br.readLine()) != null) {
        current = buffer.split(delimiter);
        if(current.length !=2){
            throw new Exception("File format is not respected");
        }

        marbles = new int[Integer.parseInt(current[0])][Integer.parseInt(current[1])];

        int count = 0;
        while ((buffer = br.readLine()) != null) {
            current = buffer.split(delimiter);

            for (int i=0;i<current.length;i++){
                marbles[count][i] = Integer.parseInt(current[i]);

            }
            count++;
        }
    }

    br.close();

    return marbles;
}

I read a file using as InputStream the one i get from the getAssets().open() method.

Here's the csv file:

5;11
1;1;2;1;1;2;1;1;1;2;-1
1;2;1;1;2;2;1;2;2;1;-1
2;2;1;2;1;2;2;1;1;2;-1
1;1;2;1;1;1;1;2;1;2;-1
2;2;1;2;2;1;2;1;1;1;-1

I get the error in the first line, but it clearly shows that the string which causes it is a proper "5".

Error:

java.lang.NumberFormatException: Invalid int: "5"

which is of course caused by the portion of code which tries to convert the string to an integer.


Solution

  • My wild guess is that your file contains a BOM at the beginning of its text stream which is confusing your parser. You can use the file command on a *NIX system to verify this.

    Try swapping that first line with another and see if you get the same error with the first number on another line. If you were set up the BOM, google "removing bom from utf-8" for further instructions.