List <Byte> to String, can you help reorganize this (small) method?
We use this method of little utility. But we do not like it. Since this is not very important (it still works ...), we forgot it.
But this is ugly, because we need to go through the entire array, only to convert from Byte[]to Byte[].
I'm looking for:
- to pass
Byte[]inByte[]without going through it - or for a utility method to add a list to a 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);
}
+5
8 answers
java.nio -
public static String byteListToString(List<Byte> l, Charset cs)
throws IOException
{
final int CBUF_SIZE = 8;
final int BBUF_SIZE = 8;
CharBuffer cbuf = CharBuffer.allocate(CBUF_SIZE);
char[] chArr = cbuf.array();
ByteBuffer bbuf = ByteBuffer.allocate(BBUF_SIZE);
CharsetDecoder dec = cs.newDecoder();
StringWriter sw = new StringWriter((int)(l.size() * dec.averageCharsPerByte()));
Iterator<Byte> itInput = l.iterator();
int bytesRemaining = l.size();
boolean finished = false;
while (! finished)
{
// work out how much data we are likely to be able to read
final int bPos = bbuf.position();
final int bLim = bbuf.limit();
int bSize = bLim-bPos;
bSize = Math.min(bSize, bytesRemaining);
while ((--bSize >= 0) && itInput.hasNext())
{
bbuf.put(itInput.next().byteValue());
--bytesRemaining;
}
bbuf.flip();
final int cStartPos = cbuf.position();
CoderResult cr = dec.decode(bbuf, cbuf, (bytesRemaining <= 0));
if (cr.isError()) cr.throwException();
bbuf.compact();
finished = (bytesRemaining <= 0) && (cr == CoderResult.UNDERFLOW);
final int cEndPos = cbuf.position();
final int cSize = cEndPos - cStartPos;
sw.write(chArr, cStartPos, cSize);
cbuf.clear();
}
return sw.toString();
}
, - .
0
StringBuilder:
public static String byteListToString(List<Byte> l) {
if (l == null) {
return "" ;
}
StringBuilder sb = new StringBuilder(l.size());
for (Byte current : l) {
sb.append((char)current);
}
return sb.toString();
}
,
public static String byteListToString(List<Byte> l) {
if (l == null) {
return "" ;
}
ByteArrayOutputStream bout = new ByteArrayOutputStream(l.size());
for (Byte current : l) {
bout.write(current);
}
return bout.toString("UTF-8");
}
, ByteArrayOutputStream . . UnsupportedEncodingException - -.
-1
Take a look at the BitConverter class, I think it does what you want. Use it in combination with the List.toArray () method.
-2