【发布时间】:2014-07-08 12:26:55
【问题描述】:
我有一个ByteArrayOutputStream,它包含一个大小为 750MB 的 XML 的字节表示。
我需要把它转换成字符串。
我写道:
ByteArrayOutputStream xmlArchive = ...
String xmlAsString = xmlArchive.toString(UTF8);
尽管我使用 4GB 的堆大小,但我得到 java.lang.OutOfMemoryError: Java heap space
怎么了?我怎么知道要使用哪个堆大小?我使用的是 JDK64 位
更新
我需要它作为字符串来删除"<?xml"之前的所有字符
目前我的代码是:
String xmlAsString = xmlArchive.toString(UTF8);
int xmlBegin = xmlAsString.indexOf("<?xml");
if (xmlBegin >0){
return xmlAsString.substring(xmlBegin);
}
return xmlAsString;
然后我再次将其转换为字节数组。
更新 2 ByteArrayOutputStream 是这样写的:
HttpMethod method ..
InputStream response = method.getResponseBodyAsStream();
byte[] buf = new byte[5000];
while ( (len=response.read(buf)) != -1) {
output.write(buf, 0, len);
}
len 来自响应的标头Content-Length
【问题讨论】:
-
你真的需要它作为内存中的字符串吗?之后你打算用它做什么?请记住,
ByteArrayOutputStream.toString()始终使用平台默认编码,这可能不是一个好主意。 -
“请记住,ByteArrayOutputStream.toString() 总是使用平台默认编码,这可能不是一个好主意”不会像 UTF-8 那样发送变量影响它?我会更新我的问题
-
xmlArchive.toString(UTF8);
-
一个字符串字符需要 2 个字节。 -- 除此之外:拥有这个字符串的想法是什么?
-
对。假设字节是真正的 UTF-8 表示,那就更好了......但我仍然会尽量避免这样做。你真正想要达到什么目的?在内存中拥有一个 1.5GB 的 char 数组确实不能很好地扩展......