HttpResponse responseGet;
try {
responseGet = client.execute(get);
switch (responseGet.getStatusLine().getStatusCode()) {
case 200:
File SDCardRoot = Environment.getExternalStorageDirectory();
File directory = new File(SDCardRoot
+ "/OfflineDocuments/"
+ (document.getPath() == null ? ""
: (document.getPath() + "/")));
directory.mkdirs();
File file = new File(directory, fileName);
InputStream is = responseGet.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
break;
default:
Log.e("Statuscode", "Unexpected status code: "
+ responseGet.getStatusLine().getStatusCode());
break;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
This works for small documents. But for documents larger than a few MB this code crashes with “OutOfMemoryException”. Any idea?
You’re slurping the file into memory in its entirety, then you write that buffered file out to storage. Instead, skip the buffering and write the pieces to storage as they come in.
note… not an android developer, so no idea if this would actually work, so treat this as pseudo-code.