16

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

artem
  • 16,382
  • 34
  • 113
  • 189
  • 2
    @Nick is joking. You may note that he is calling `toLowerCase()` on the string `"Byte[]"`. Yeah, I know, by explaining it, I ruined the joke. – Oded Jun 21 '11 at 19:31
  • @Oded explanations of jokes are funny in themselves :) – Atreys Jun 21 '11 at 19:55

3 Answers3

29

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

Vitaly Olegovitch
  • 3,509
  • 6
  • 33
  • 49
tim_yates
  • 167,322
  • 27
  • 342
  • 338
9
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 :)

CAMOBAP
  • 5,523
  • 8
  • 58
  • 93
jacktrades
  • 7,224
  • 13
  • 56
  • 83
2

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    My only contention with this is that any writes to the ByteArrayOutputStream now require `try{}catch(){}` for no real reason other than that it inherits from OutputStream. – Huckle Apr 09 '13 at 21:02
  • I'd say this is an interesting comment to the question rather than an answer. – Tomas Vinter Jun 19 '13 at 07:54
  • @TomasVinter For me, sometimes the best answer is don't do that, do this instead. i.e. you are just making a bad idea worse. ;) – Peter Lawrey Jun 19 '13 at 12:43