我想保存一个非常大的在线xml文件(大约33mb)。我试图在StringBuilder中获取xml文件,转换为字符串,然后通过FileOutputStream将文件保存在内部存储/ Sdcard中。
但是我的内存不足,应用程序崩溃了。当我尝试从StringBuilder获取字符串中的值时发生崩溃。
这是我目前的代码:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("sorry cant paste the actual link due copyrights.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String result = sb.toString();
System.out.println(result);
FileOutputStream fos = openFileOutput("test.xml", Context.MODE_PRIVATE);
fos.write(sb.toString().getBytes());
fos.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
答案 0 :(得分:2)
你的问题是它需要大量的应用程序内存,因为xml-string完全被编码到内存中。
您可以通过处理litte 1kb块中的数据来避免这种情况,如下所示:
is = httpEntity.getContent();
FileOutputStream fos = openFileOutput("test.xml", Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))>0){
fos.write(buffer, 0, length);
}
fos.flush();
fos.close();
is.close();
答案 1 :(得分:1)
你能试试下面的代码吗?
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
FileOutputStream fos = openFileOutput("test.xml", Context.MODE_PRIVATE);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
if (sb.toString().length() > 10000) {
fos.write(sb.toString().getBytes());
fos.flush();
sb = new StringBuilder();
}
}
is.close();
fos.close();