The fastest way to copy text from a file to HttpServletResponse

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

I actually copy byte by byte in a loop, from a buffered Reader to response.getWriter (), but I believe there should be a faster and easier way to do this.

Thanks!

+3
source share
3 answers

I like to use the read () method, which takes an array of bytes, since you can adjust 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();
}
+5
source
+4

Here's 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();
+2
source

Source: https://habr.com/ru/post/1716858/


All Articles