Posted By

peceps on 10/15/10


Tagged

file fast servlet Reading


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

peceps
kubaitis
studioevoque


Super fast FileServlet


 / Published in: Java
 

  1. private void output(HttpServletResponse response, String filePathAndFileName, String mimeType)
  2. throws IOException {
  3.  
  4. File file = new File(filePathAndFileName);
  5.  
  6. // set response headers
  7. response.setContentType((mimeType != null) ? mimeType : "application/octet-stream");
  8. response.setContentLength((int) file.length());
  9.  
  10.  
  11.  
  12. // read and write file
  13. ServletOutputStream op = response.getOutputStream();
  14. // 128 KB buffer
  15. int bufferSize = 131072;
  16. FileInputStream fileInputStream = new FileInputStream(file);
  17. FileChannel fileChannel = fileInputStream.getChannel();
  18. // 6x128 KB = 768KB byte buffer
  19. ByteBuffer bb = ByteBuffer.allocateDirect(786432);
  20. byte[] barray = new byte[bufferSize];
  21. int nRead, nGet;
  22.  
  23. try {
  24. while ((nRead = fileChannel.read(bb)) != -1) {
  25. if (nRead == 0)
  26. continue;
  27. bb.position(0);
  28. bb.limit(nRead);
  29. while (bb.hasRemaining()) {
  30. nGet = Math.min(bb.remaining(), bufferSize);
  31. // read bytes from disk
  32. bb.get(barray, 0, nGet);
  33. // write bytes to output
  34. op.write(barray);
  35. }
  36. bb.clear();
  37. }
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. } finally {
  41. bb.clear();
  42. fileChannel.close();
  43. fileInputStream.close();
  44. }
  45. }

Report this snippet  

You need to login to post a comment.