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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:51:46  来源:igfitidea点击:

Java - Byte[] to byte[]

javabytebytearray

提问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 langArrayUtils类中的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 在这个答案中做出了贡献:)