【发布时间】:2012-03-22 09:53:38
【问题描述】:
我从 SocketChannel 连续读取 BLOCKSIZE(例如 512)字节块到 ByteBuffer 中。然后,我想将 ByteBuffer 内容附加到 byte[] 并进行下一轮。结果将是一个 byte[],其中包含从 SocketChannel 读取的所有字节。
现在,System.arraycopy(...) 按预期工作。但是当我使用 ByteBuffer 的 get(result, offset, length) 时,什么都没有写入。结果数组值保持为零。
为什么会这样?
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();
}
【问题讨论】:
标签: java bytearray bytebuffer