1

How do you save an entity to SDCard, in a streamed manner (To avoid memory issues).

I cant find any solid documentation on the matter.

        response = httpClient.execute(request);

        BufferedHttpEntity responseEntity = new BufferedHttpEntity(response.getEntity());

        FileOutputStream fos = new FileOutputStream(Files.SDCARD + savePath);

        responseEntity.writeTo(fos);

        fos.flush();
        fos.close();

This gives me the file, but with no contents. (2KB in size). So its not writing properly.

The server is sending a FileStream. Which I have confirmed to work.

Charles
  • 50,943
  • 13
  • 104
  • 142
IAmGroot
  • 13,760
  • 18
  • 84
  • 154

1 Answers1

2

I would try this approach:

HttpResponse response = httpClient.execute(post);    

InputStream input = response.getEntity().getContent();
OutputStream output = new FileOutputStream("path/to/file");
int read = 0;

byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) != -1) {
    output.write(bytes, 0, read);
}
output.close();

Hope it helps. Cheers.

kraxor
  • 649
  • 8
  • 16
  • Thanks, this does work. So accepting. However, when changing the code, i realized a bug in the URL i was using. (which was preventing your method from working too). I will go back and try my old code too. But either should work. Edit: Tested, and my code does work. – IAmGroot Oct 31 '13 at 12:05
  • Your method is better, as it truely streams, to avoid memory overflow. – IAmGroot Oct 31 '13 at 15:02