Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Do not do that for large files:</p> <pre><code>byte[] bytesToSend = myFile.getBytes(); </code></pre> <p>This is inefficient and you need heap space for storing the whole file data. You're wasting lots of heap space when you first read the file completly and afterwards write it completly.</p> <p>Instead read/write the file data in chunks of specific size from file directly to the response. You can write code on your own or just use a utility class like <code>IOUtils</code> from Apache Commons IO.</p> <p>It is important to not read the whole file first before you write it. Instead do it in smaller chunks. Use streams here and avoid anything that deals with byte[] except for buffering and the small chunks.</p> <p>Edit: Here's some code with Apache IO...</p> <pre><code>public static void main(String[] args) { HttpExchange exchange = ...; OutputStream responseBody = null; try { File file = new File("big-file.txt"); long bytesToSkip = 4711; //detemine how many bytes to skip exchange.sendResponseHeaders(200, file.length() - bytesToSkip); responseBody = exchange.getResponseBody(); skipAndCopy(file, responseBody, bytesToSkip); } catch (IOException e) { // handle it } finally { IOUtils.closeQuietly(responseBody); } } private static void skipAndCopy(File src, @WillNotClose OutputStream dest, long bytesToSkip) throws IOException { InputStream in = null; try { in = FileUtils.openInputStream(src); IOUtils.skip(in, bytesToSkip); IOUtils.copyLarge(in, dest); } finally { IOUtils.closeQuietly(in); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload