我正在连续地从SocketChannel读取BLOCKSIZE(例如512)个字节块到ByteBuffer中。然后,我想将ByteBuffer内容追加到byte []并进入下一轮。结果将是一个byte [],其中包含从SocketChannel读取的所有字节。
现在,System.arraycopy(...)按预期工作。但是当我使用ByteBuffer的get(结果,偏移量,长度)时,什么都没写。结果数组值保持为零。
为什么?
public final static int BLOCKSIZE = 512;
public byte[] getReceivedData() {
int offset = 0, read;
byte[] result = {};
ByteBuffer buffer = ByteBuffer.allocate(BLOCKSIZE);
try {
while (true) {
read = _socketChannel.read(buffer);
if (read < 1) {
// Nothing was read.
break;
}
// Enlarge result so we can append the bytes we just read.
result = Arrays.copyOf(result, result.length + read);
// This works as expected.
System.arraycopy(buffer.array(), 0, result, offset * BLOCKSIZE, read);
// With this, however, nothing is written to result. Why?
buffer.get(result, offset * BLOCKSIZE, read);
if (read < BLOCKSIZE) {
// Nothing left to read from _socketChannel.
break;
}
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
修改
我注意到offset++
也丢失了。因此,如果频道上有超过BLOCKSIZE
个字节,事情会搞砸......
无论如何,ByteArrayOutputStream
确实让事情变得更简单,所以我决定使用它。
工作代码:
public byte[] getReceivedData() {
int read;
ByteArrayOutputStream result = new ByteArrayOutputStream();
ByteBuffer buffer = ByteBuffer.allocate(BLOCKSIZE);
try {
while (true) {
buffer.clear();
read = _socketChannel.read(buffer);
if (read < 1) {
break;
}
result.write(buffer.array(), 0, read);
if (read < BLOCKSIZE) {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toByteArray();
}
答案 0 :(得分:2)
flip()
之前需要get()
缓冲区,之后需要compact()
。
如果read == -1
你不仅需要突破循环而且还要关闭频道。
答案 1 :(得分:0)
您的结果数组长度为0,无法保存任何信息。字节数组不会增长,并且您无法附加缓冲区的内容。使用java.io.ByteArrayOutputStream来累积结果。