Fastest way to copy text from a File to a HttpServletResponse

file, java, servlets, stream

Solution

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();
}

Problem

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!

Original source