将<byte>列表到String,你能帮助重构这个(小)方法吗?</byte>

时间:2009-07-08 08:42:26

标签: java arrays bytearray

我们使用这种小实用方法。但我们不喜欢它。因为它不是非常重要(无论如何......),我们已经忘记了它 但那很难看,因为我们必须通过整个阵列,才能进行转换 它从Byte[]byte[] 我在找:

  • 用于在Byte[]中投射byte[]而不通过它的方式
  • 或用于将List强制转换为字符串
  • 的实用程序方法

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);
}

8 个答案:

答案 0 :(得分:8)

你的方法几乎是唯一的方法。您可能会找到一个可以完成全部或部分内容的外部库,但它基本上会做同样的事情。

但是,代码中有一件事是潜在的问题:调用new String(array)时,您使用平台默认编码将字节转换为字符。平台编码在操作系统和区域设置之间有所不同 - 使用它几乎总是等待发生的错误。它取决于你从哪里得到这些字节,但是它们的编码应该在某处指定,作为参数传递给方法并用于转换(通过使用带有第二个参数的String构造函数)。

答案 1 :(得分:3)

import org.apache.commons.lang.ArrayUtils;

...

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

byte[] b =  ArrayUtils.toPrimitive(bytes);

答案 2 :(得分:1)

没有任何额外的库(例如apache commons)你的方法很好

答案 3 :(得分:1)

Minor nit:

if (l == null || l.isEmpty() ) {
    return "" ;
}

避免为空列表创建空字符串。

答案 4 :(得分:1)

Guava提供了许多有用的primitive utilities,包括Bytes类,可以对Byte的集合进行此操作和其他操作。

private static String toString(List<Byte> bytes) {
  return new String(Bytes.toArray(bytes), StandardCharsets.UTF_8);
}

答案 5 :(得分:0)

您可以使用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();
}

但我真的不认为我会推荐这么简单的东西。

答案 6 :(得分:-1)

一个选项可能是使用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 - 你需要尝试在某处捕获它。

答案 7 :(得分:-2)

查看BitConverter课程,我认为它可以满足您的需求。将它与List.toArray()方法结合使用。

相关问题