java.lang.NumberFormatException:无效的int:" 5"

时间:2015-07-29 13:31:28

标签: java android numberformatexception

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

这是造成这个奇怪错误的代码:

 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

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

错误:

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

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

3 个答案:

答案 0 :(得分:4)

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

尝试将第一行与另一行进行交换,看看是否与另一行的第一个号码出现相同的错误。如果您设置了BOM,请点击“从utf-8中删除bom”以获取进一步的说明。

答案 1 :(得分:1)

导致此行为的唯一可能原因是文件中的不可打印符号。看看这个问题: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}", "?"))]

答案 2 :(得分:0)

在我的情况下,自定义属性没有分配任何值的问题。

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

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

相关问题