java.lang.NumberFormatException:无效整数:“5”

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

我尝试读取一个 .txt 文件,它基本上是一个 CSV 文件,位于 Android 的 Assets 文件夹中。 第一行是文件的行数和列数 其余由值组成,我使用“;”彼此分开。

这是导致这个奇怪错误的代码:

 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;
}

我使用从 getAssets().open() 方法获得的 InputStream 读取了一个文件。

这是 csv 文件:

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

我在第一行收到错误,但它清楚地表明导致错误的字符串是正确的“5”。

错误:

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

这当然是由试图将字符串转换为整数的代码部分引起的。

我的大胆猜测是您的文件在其文本流的开头包含一个 BOM,这会使您的解析器感到困惑。您可以在 *NIX 系统上使用 file 命令来验证这一点。

尝试将第一行与另一行交换,看看另一行的第一个数字是否出现相同的错误。如果您设置了 BOM,google "removing bom from utf-8" 以获得进一步的说明。

导致此行为的唯一可能原因是您的文件中有不可打印的符号。看看这个问题:How can I replace non-printable Unicode characters in Java? 并将给定函数应用于您的所有值,即:

marbles = new int[Integer.parseInt(current[0].replaceAll("\p{C}", "?"))][Integer.parseInt(current[1].replaceAll("\p{C}", "?"))]

在我的例子中,问题是自定义定义的属性没有分配任何值。

<FrameLayout
    android:id="@+id/header"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="?attr/image_visibility">

</FrameLayout>

这是自定义属性定义:

<attr name="image_visibility">
    <enum name="visible" value="0"/>
    <enum name="invisible" value="1"/>
    <enum name="gone" value="2"/>
</attr>

问题是我没有为此自定义属性分配任何值。
删除该自定义属性或为其分配一个值将修复该错误。