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 :
Byte[]
in byte[]
without going through it
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);
}
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).
import org.apache.commons.lang.ArrayUtils;
...
Byte[] bytes = new Byte[l.size()];
l.toArray(bytes);
byte[] b = ArrayUtils.toPrimitive(bytes);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With