I'm trying to download file at my android device. This is my code:
InputStream in = null;
ByteArrayOutputStream out = null;
FileOutputStream fos = null;
try {
URL link = new URL(fileURL);
in = new BufferedInputStream(link.openStream());
out = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int n, bytesBuffered = 0;
while (-1 != (n = in.read(buf))) {
bytesBuffered += n;
out.write(buf, 0, n);
if (bytesBuffered >1048576) {
bytesBuffered = 0;
out.flush();
}
}
byte[] response = out.toByteArray();
fos = new FileOutputStream(filePath);
fos.write(response);
return true;
} catch (Throwable e) {
e.printStackTrace();
return false;
} finally {
//closing streams
}
It fails at out.write(buf, 0, n);
with out of memory error. What is wrong? I've read I'm able to set bigger heap size at manifest, but I don't find it a good solution. What is wrong?