views:

405

answers:

3

Hi,

I need a very fast way to copy text from a file to the body of a HttpServletResponse.

Actually I'm copying byte by byte in a loop, from a bufferedReader to the response.getWriter() but I believe there must be a faster and more straightforward way of doing it.

Thanks!

+3  A: 

I like using the read() method that accepts a byte array since you can tweak the size and change the performance.

public static void copy(InputStream is, OutputStream os) throws IOException {
      byte buffer[] = new byte[8192];
      int bytesRead;

      BufferedInputStream bis = new BufferedInputStream(is);
      while ((bytesRead = bis.read(buffer)) != -1) {
              os.write(buffer, 0, bytesRead);
      }
      is.close();
      os.flush();
      os.close();
}
Wayne Young
+1  A: 

This is how I do it in my Servlet with a 4K buffer,

   // Send the file.
    OutputStream out = response.getOutputStream();
    BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
    byte[] buf = new byte[4 * 1024]; // 4K buffer
    int bytesRead;
    while ((bytesRead = is.read(buf)) != -1) {
        out.write(buf, 0, bytesRead);
    }
    is.close();
    out.flush();
    out.close();
ZZ Coder
A: 

There's no need to do this stuff yourself. It is such a common requirement that open source, battle-tested, optimised solutions exist.

Apache Commons IO has an IOUtils class with a range of static copy methods. Perhaps you could use

IOUtils.copy(reader, writer);

http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#copy(java.io.Reader, java.io.Writer)

Steve McLeod
Thanks Steve, I' sure that's a great solution but I'm trying to keep external references to the bare minimum.
Pablo Fernandez