Есть InputStream в котором записана последовательность известной длины 32 битных чисел в LittleEndian порядке байт.
Вопрос, как наиболее эффективно эту последовательность считать в массив? Сейчас делаю так
public int[] read(InputStream strm, int count) throws IOException {
int[] res = new int[count];
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.order(ByteOrder.LITTLE_ENDIAN);
byte[] arr = buffer.array();
for (int i = 0; i < count; i++) {
if (strm.read(arr, 0, 4) < 4)
throw new IOException("Stream read error");
res[i] = buffer.getInt(0);
}
return res;
}
Но хотелось бы как-то так
public int[] read(InputStream strm, int count) throws IOException {
int[] res = new int[count];
int size = count * 4;
if (strm.read((byte[])res, 0, size) < size)
throw new IOException("Stream read error");
return res;
}
Т.е. одним чтением сразу считать весь массив.
Пробовал так
public int[] readArray(InputStream strm, int count) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(4 * count);
buffer.order(ByteOrder.LITTLE_ENDIAN);
byte[] arr = buffer.array();
if (strm.read(arr) < arr.length)
throw new IOException("Stream read error");
IntBuffer res = buffer.asIntBuffer();
return res.array();
}
Но на return res.array(); вылетает UnsupportedOperationException
Если работать с IntBuffer
IntBuffer buffer = IntBuffer.allocate(4 * count);
то у него невозможно поменять порядок байт
Вот такой вариант
public int[] readArray(InputStream strm, int count) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(4 * count);
buffer.order(ByteOrder.LITTLE_ENDIAN);
byte[] arr = buffer.array();
if (strm.read(arr) < arr.length)
throw new IOException("Stream read error");
IntBuffer intBuffer = buffer.asIntBuffer();
int[] res = new int[count];
intBuffer.get(res);
return res;
}
позволяет считать за одну операцию, но за счет двойного потребления памяти. Тоже не комильфо.
Сборка персонального компьютера от Artline: умный выбор для современных пользователей