Я последовательно читаю блоки байтов BLOCKSIZE (например, 512) из SocketChannel в ByteBuffer. Затем я хотел бы добавить содержимое ByteBuffer в байт [] и перейти к следующему раунду. Результатом будет байт [], содержащий все байты, которые были прочитаны из SocketChannel.
Теперь System.arraycopy (...) работает как положено. Но когда я использую get ByteBuffer (результат, смещение, длина), ничего не пишется. Значения массива результата остаются обнуленными.
Почему это?
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;
}
EDIT:
Я заметил, что 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();
}