Java 将字节数组转换为 List<Byte>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4231674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting an array of bytes to List<Byte>
提问by Eternal Noob
I could think of these things,
能想到这些,
Arrays.asList(byte[])
convertsbyte[]
toList<byte[]>
,- looping through byte array and add each element to list
Arrays.asList(byte[])
转换byte[]
为List<byte[]>
,- 循环遍历字节数组并将每个元素添加到列表中
I was just wondering Is there any library function to do that?
我只是想知道是否有任何库函数可以做到这一点?
采纳答案by chkal
For Byte[]
instead of byte[]
this would work:
因为Byte[]
而不是byte[]
这样会起作用:
Byte[] array = ....
List<Byte> list = Arrays.asList(array);
回答by peenut
Library Apache Commons Langhas ArrayUtils.toObject, which turns a primitive array to a typed object array:
库Apache Commons Lang有 ArrayUtils.toObject,它将原始数组转换为类型化对象数组:
int array[] = { 1, 2, 3 };
List<Integer> list = Arrays.asList(ArrayUtils.toObject(array));
回答by Ammar
byte[] byteArray;
List<Byte> medianList=new ArrayList<>();
int median=0,count=0;
Path file=Paths.get("velocities.txt");
if(Files.exists(file)){
byteArray=Files.readAllBytes(file);
}
medianList.addAll(Arrays.asList(byteArray));
回答by Jens Nyman
As thispost suggests: the guava Bytes classcan help out:
byte[] bytes = ...
List<Byte> byteList = Bytes.asList(bytes);
回答by Datz
I think the simplest pure Java way, without additional libraries, is this:
我认为最简单的纯 Java 方式,没有额外的库,是这样的:
private static List<Byte> convertBytesToList(byte[] bytes) {
final List<Byte> list = new ArrayList<>();
for (byte b : bytes) {
list.add(b);
}
return list;
}
But better check twice if you really need to convert from byte
to Byte
.
但如果您真的需要从 转换为byte
,最好检查两次Byte
。