【问题标题】:Reading from InputStream to byte[] throws IndexOutOfBoundsException从 InputStream 读取到 byte[] 抛出 IndexOutOfBoundsException
【发布时间】:2012-05-20 12:26:37
【问题描述】:

我显然不知道问题出在哪里!首先我要求客户将他要发送的byte[]的长度发送给我,然后我这样读取它的长度。

int i = 323292; // length of incoming Byte[]
byte[] b = new byte[i]; 
int readBytes=inputStream.read(b,0,b.length);

但它总是读取 readBytes 小于 i。而且我确信客户端会发送整个byte[]

我试图把它放在一个循环中,直到我读取的字节总数为 i,但我总是在第二次迭代后得到 IndexOutOfBoundsException!这是代码

boolean flag = true;
int i = 323292;
int threshold = 0;
byte[] b = new byte[i];
int read = 0;
while (flag) {
    if (threshold < i) {
        System.out.println(threshold);
        try {
            read = inputStreamFromClient.read(b, threshold, b.length);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        threshold = threshold + read;
    } else {
        flag = false;
    }
}

有什么想法吗?

【问题讨论】:

标签: java sockets networking inputstream


【解决方案1】:

这个:

read = inputStreamFromClient.read(b, threshold, b.length);

应该是:

read = inputStreamFromClient.read(b, threshold, b.length - threshold);

【讨论】:

  • 你是救生员!谢谢!
  • threshold 通常称为offset。请参阅 API 文档。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
  • 2013-11-08
  • 2023-03-28
  • 1970-01-01
  • 2011-01-06
相关资源
最近更新 更多