Java - 字节 [] 到字节 []
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6430841/
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
Java - Byte[] to byte[]
提问by artem
There is Vector and DataOutputStream. I need to write bytes from Vector (toArray returns Byte[]) to the stream, but it understands byte[] only. How to convert Byte[] to byte[] ?
有 Vector 和 DataOutputStream。我需要将 Vector 中的字节(toArray 返回 Byte[])写入流,但它只理解 byte[]。如何将 Byte[] 转换为 byte[] ?
采纳答案by tim_yates
You could use the toPrimitivemethod in the Apache Commons langlibrary ArrayUtilsclass?
您可以使用Apache Commons lang库 ArrayUtils类中的toPrimitive方法吗?
回答by Peter Lawrey
A Vector<Byte> is about as inefficient structure as you could use to store bytes. I would serious consider using something more efficient line ByteArrayOutputStream which has a toByteArray() method. i.e. don't just convert the Vector but remove it from the code.
Vector<Byte> 与用于存储字节的结构一样低效。我会认真考虑使用更有效的行 ByteArrayOutputStream ,它具有 toByteArray() 方法。即不只是转换 Vector 而是将其从代码中删除。
回答by Hymantrades
byte[] toPrimitives(Byte[] oBytes)
{
byte[] bytes = new byte[oBytes.length];
for(int i = 0; i < oBytes.length; i++) {
bytes[i] = oBytes[i];
}
return bytes;
}
Inverse:
逆:
// byte[] to Byte[]
Byte[] toObjects(byte[] bytesPrim) {
Byte[] bytes = new Byte[bytesPrim.length];
int i = 0;
for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing
return bytes;
}
freeone3000 contributed in this answer :)
freeone3000 在这个答案中做出了贡献:)