如果字节数组很大,那么
byte[] buffer = new byte[size];
int length = is.read(buffer);
is.close();
String content = new String(buffer, "UTF-8");
可能会因OutOfMemoryError
而失败(可能是因为内存碎片或缺少可用的连续字节)
如何通过Java中的块将byte[]
数组转换为String
?
答案 0 :(得分:0)
1.计算应用minimum_heap_memory_in_bytes=maximum_heap_memory_in_bytes/(4 or >4)
2.从ByteArray
到PreviousByteCount
的块中阅读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;
}