System.arraycopy
выбрасывает исключение когда ему передают массивы разных типов:
..., if any of the following is true, an ArrayStoreException is thrown and the destination is not modified:
...
The src argument refers to an array with a reference component type and the dest argument refers to an array with a primitive component type.
... если выполняется одно из следующих условий, выбрасывается ArrayStoreException и массив назначения не изменяется
...
Аргумент src
— массив ссылочного типа, а аргумент dest
— массив примитивного типа.
Я не знаю удобного стандартного способа преобразовать Byte[]
в byte[]
. Можно подключить Apache Commons и использовать ArrayUtils
, что немного сократит код:
List<Byte> entire = new ArrayList<>();
for (FileItem item : items) {
Byte[] itemArray = ArrayUtils.toObject(item.get());
entire.addAll(Arrays.asList(itemArray));
}
Byte[] bytes = entire.toArray(new Byte[entire.size()]);
return ArrayUtils.toPrimitive(bytes);
Чтобы избежать многократного создания массивов можно создать большой массив для результата и копировать все остальные в него, например, так:
//собираем массивы
List<byte[]> contents = new ArrayList<>();
for (FileItem item : items) {
contents.add(item.get());
}
//считаем суммарную длину
int totalLength = 0;
for (byte[] content : contents) {
totalLength += content.length;
}
//собираем в один массив
byte[] entire = new byte[totalLength];
int offset = 0;
for (byte[] content : contents) {
System.arraycopy(content, 0, entire, offset, content.length);
offset += content.length;
}
return entire;
Метод можно сразу разбить на три:
public static byte[] receive(final List<FileItem> items) {
List<byte[]> contents = getContents(items);
int totalLength = calculateTotalLength(contents);
return mergeAll(contents, totalLength);
}
или на два:
public static byte[] receive(final List<FileItem> items) {
return mergeAll(getContents(items));
}