【问题标题】:String.getBytes() throws a Nullpointer Exception [duplicate]String.getBytes() 抛出 Nullpointer 异常 [重复]
【发布时间】:2014-08-24 23:36:56
【问题描述】:

我正在尝试逐行读取文件并将其保存到字节数组中,但由于某种原因 String.getBytes() 会引发 Nullpointer 异常。

我做错了什么?

public static void main(String[] args) {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    byte[][] bytes = null;
    try {
        String data;
        int i = 0;
        while((data = br.readLine()) != null) {
            bytes[i] = data.getBytes(); // THROWS A NULLPOINTER EXCEPTION HERE
            i++;
        }
        System.out.println(bytes.length);

    } catch (IOException e)
        e.printStackTrace();
    }

}

【问题讨论】:

  • byte[][] bytes = null; -- 你从来没有真正创建过数组。
  • YemSalat - 你在使用像 eclipse 这样的 IDE 吗?
  • @BoratSagdiyev,完全正确,它没有抛出异常。它仅在我尝试运行实际程序时出现。

标签: java string byte bufferedreader


【解决方案1】:

您的字节数组bytes 为空。为什么不使用ArrayList

ArrayList<byte[]> bytes = new ArrayList<>();

然后在您的代码中:

bytes.add(data.getBytes());

【讨论】:

  • 谢谢,这似乎是一个更好的解决方案。我还需要声明类型吗?像这样:ArrayList&lt;Byte&gt;Edit您在我发布之前编辑过 - 非常感谢,现在已经清楚了。
【解决方案2】:

这是因为您从未将 bytes 初始化为 anyting 而是 null

 byte[][] bytes = null;

【讨论】:

  • 谢谢!但我不知道每个数组的大小,而且读取的每一行的大小可能不同。我应该改用 ArrayList 吗?
  • @YemSalat - 实际上,当我执行你的代码时,我没有得到任何 npe。
  • 我在 Eclipse 中没有得到,但在命令行中运行时会得到。
【解决方案3】:

问题是bytes 在您尝试分配给它时是null(您从未实例化它!)。试试这个:

byte[][] bytes = new bytes[N][];

您必须至少指定bytes 矩阵中的行数填充它之前。我不知道N 的值应该是什么,如果在循环开始时它是未知的,那么我们不能使用byte[][] 来存储结果——在这种情况下,可变长度数据结构是必需的,例如 ArrayList&lt;byte[]&gt; 可以解决问题:

String data;
List<byte[]> bytes = new ArrayList<byte[]>();
while ((data = br.readLine()) != null) { // we don't need `i` for anything
    bytes.add(data.getBytes());
}
System.out.println(bytes.size());        // this prints the number of rows

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    相关资源
    最近更新 更多