如何通过块将字节数组转换为字符串?

时间:2016-05-27 09:29:18

标签: java android string bytearray

如果字节数组很大,那么

byte[] buffer = new byte[size];
int length = is.read(buffer);
is.close();
String content = new String(buffer, "UTF-8");

可能会因OutOfMemoryError而失败(可能是因为内存碎片或缺少可用的连续字节)

如何通过Java中的块将byte[]数组转换为String

3 个答案:

答案 0 :(得分:0)

1.计算应用minimum_heap_memory_in_bytes=maximum_heap_memory_in_bytes/(4 or >4)

的最小堆内存

2.从ByteArrayPreviousByteCount的块中阅读PreviousByteCount+minimum_heap_memory_in_bytes

答案 1 :(得分:0)

我使用这种方法,希望它能帮助

public String getBase64FromByteArray(byte[] byteArray){
    String base64 = "";
    try{
        base64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
    }catch(Exception e){
        e.printStackTrace();
        return null;
    }
    return base64;
}

答案 2 :(得分:0)

你可以做类似的事情......

 public String getBinaryString()
 {        
      int nRead;
      InputStream inputStream = <your input stream>
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      byte[] data = new byte[16384];
      while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
      buffer.flush();
      byte[] encoded = Base64.encodeBase64((byte[])buffer.toByteArray());
      String binaryString = new String(encoded, "UTF-8");
      return binaryString;
 }