Basic Coder
Basic Coder

Reputation: 11422

Out of memory when downloading a file

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?

Upvotes: 1

Views: 1832

Answers (2)

Jan Zyka
Jan Zyka

Reputation: 17888

You are simply trying to read the whole file into memory and your JVM has not enough memory available. You probably want to write to the file inside your while loop rather than appending it to the buffer.

Upvotes: 0

Marc B
Marc B

Reputation: 360682

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.

FileOutputStream fos = new FileOutputStream(file);
while ((current = bis.read()) != -1) {
    fos.write(current);
}
fos.close();

note... not an android developer, so no idea if this would actually work, so treat this as pseudo-code.

Upvotes: 1

Related Questions