Java - Byte[] to byte[]

自作多情 提交于 2019-12-06 19:03:07

问题


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[] ?


回答1:


You could use the toPrimitive method in the Apache Commons lang library ArrayUtils class?




回答2:


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 :)




回答3:


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.



来源:https://stackoverflow.com/questions/6430841/java-byte-to-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!