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文档。