Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<Byte> to String, can you help refactor this ( small ) method?

We use this small utility method. But we don't like it. Since it's not very crucial (it works anyway ... ) , we have forgotten it.
But that's ugly, because we have to go through the whole array, only to convert it from Byte[] to byte[].
I'm looking :

  • for a way to cast the Byte[] in byte[] without going through it
  • or for a utility method for cast a List into string

public static String byteListToString(List<Byte> l, Charset charset) {
    if (l == null) {
        return "";
    }
    byte[] array = new byte[l.size()];
    int i = 0;
    for (Byte current : l) {
        array[i] = current;
        i++;
    }
    return new String(array, charset);
}
like image 747
Antoine Claval Avatar asked Jul 08 '09 08:07

Antoine Claval


Video Answer


2 Answers

Your method is pretty much the only way to do it. You may find an external library that does all or part of it, but it will essentially do the same thing.

However, there is one thing in your code that is a potential problem: When calling new String(array), you are using the platform default encoding to convert the bytes to characters. The platform encoding differs between operating system and locale settings - using it is almost always a bug waiting to happen. It depends on where you're getting those bytes from, but their encoding should be specified somewhere, passed as argument to the method and used for the conversion (by using the String constructor with a second parameter).

like image 145
Michael Borgwardt Avatar answered Nov 14 '22 23:11

Michael Borgwardt


import org.apache.commons.lang.ArrayUtils;

...

Byte[] bytes = new Byte[l.size()];
l.toArray(bytes);

byte[] b =  ArrayUtils.toPrimitive(bytes);
like image 41
Rich Seller Avatar answered Nov 14 '22 22:11

Rich Seller