Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从InputStream读取字节[]会引发IndexOutfBoundsException_Java_Sockets_Networking_Inputstream - Fatal编程技术网

Java 从InputStream读取字节[]会引发IndexOutfBoundsException

Java 从InputStream读取字节[]会引发IndexOutfBoundsException,java,sockets,networking,inputstream,Java,Sockets,Networking,Inputstream,我显然不知道问题出在哪里!,首先,我要求客户向我发送他要发送的字节[]的长度,然后我像这样读取它的长度 int i = 323292; // length of incoming Byte[] byte[] b = new byte[i]; int readBytes=inputStream.read(b,0,b.length); 但它读取的readBytes总是比我少。我确信客户端会发送整个字节[] 我试着把它放在一个循环中,一直读到我的总读取字节数是I,但在第二次迭代后,我总是得到Ind

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

int i = 323292; // length of incoming Byte[]
byte[] b = new byte[i]; 
int readBytes=inputStream.read(b,0,b.length);
但它读取的readBytes总是比我少。我确信客户端会发送整个
字节[]

我试着把它放在一个循环中,一直读到我的总读取字节数是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;
    }
}
boolean标志=true;
int i=323292;
int阈值=0;
字节[]b=新字节[i];
int read=0;
while(旗帜){
如果(阈值
有什么想法吗?

这是:

read = inputStreamFromClient.read(b, threshold, b.length);
应该是:

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

你真的应该使用一个Commons IO包来节省一些编码时间和不必要的复杂性:谢谢你的帮助,我会检查它!这个简单的任务不需要第三方软件。请参阅
DataInputStream.readFully()
。您是一个救生员!谢谢而
阈值
通常称为
偏移量
。请参阅API文档。