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[]inbyte[]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);
}
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).