我明显不知道问题出在哪里!首先我要求客户端发送他要发送的byte[]
的长度,然后我读取其长度这个。从InputStream读取到byte []抛出IndexOutOfBoundsException
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;
}
}
AnyIdeas?
你真的应该使用Commons IO包中的一个给自己节省一些编码时间和不必要的复杂性:HTTP://commons.apache。 org/io/api-release/org/apache/commons/io/IOUtils.html#toByteArray(java.io.InputStream) – grahamrb
感谢您的帮助我会检查它! –
这个简单的任务不需要第三方软件。参见'DataInputStream.readFully()'。 – EJP