2

I am trying to initiate a file download from the client. All I have is an InputStream containing the binary on the server side. I somehow need to figure out a way to dump it onto an OutputStream in chunks (I tried writing the entire byte array at once and ran into an OutOfMemoryException as the file is over 100MB). Any help would be appreciated...

user1343585
  • 649
  • 1
  • 5
  • 7

1 Answers1

3

Do reading and writing concurrently.

import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;

        long size = sourceFile.length();
        if (size <= Integer.MAX_VALUE)
            response.setContentLength((int)size);

        InputStream in = FileUtils.openInputStream(sourceFile);
        OutputStream out = response.getOutputStream();
        Streams.copy(in, out, false);
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • I have to use Http and am not allowed to use any org.apache classes either – user1343585 Apr 19 '12 at 10:02
  • `Streams.copy` is just reading and writing in a loop, closing the input, here not closing the output. `openInputStream` you can easily substitute (does a bit more checking that the normal open). – Joop Eggen Apr 19 '12 at 10:39