我正在尝试将大流(4mb)转换为字符串,我最终将其转换为 JSON 数组。
当流大小很小(以 KB 为单位)时,一切正常,当它开始处理 4mb 流时,它会耗尽内存
下面是我用来将流转换为字符串的方法,我几乎尝试了所有方法,我怀疑问题出在 while 循环上。有人可以帮忙吗?
public String convertStreamToString(InputStream is)
throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try
{
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
is.close();
}
return writer.toString();
} else {
return "";
}
}
更新:好的,这是我目前到达的地方,我在正确的轨道上吗?我想我已经接近了..不确定我还能关闭或刷新什么来恢复记忆..
public String convertStreamToString(InputStream is)
throws IOException {
String encoding = "UTF-8";
int maxlines = 2000;
StringWriter sWriter = new StringWriter(7168);
BufferedWriter writer = new BufferedWriter(sWriter);
BufferedReader reader = null;
if (is == null) {
return "";
} else {
try {
int count = 0;
reader = new BufferedReader(new InputStreamReader(is, encoding));
for (String line; (line = reader.readLine()) != null;) {
if (count++ % maxlines == 0) {
sWriter.close();
// not sure what else to close or flush here to regain memory
//Log.v("Max Lines Reached", "Max Lines Reached");;
}
writer.write(line);
}
Log.v("Finished Loop", "Looping over");
} finally {
is.close();
writer.close();
}
return writer.toString();
}
}