使用 NIO 实现的一个超级快的 FileServlet详解编程语言

  
private void output(HttpServletResponse response, String filePathAndFileName, String mimeType) 
      throws IOException { 
 
    File file = new File(filePathAndFileName); 
 
    // set response headers 
    response.setContentType((mimeType != null) ? mimeType : "application/octet-stream"); 
    response.setContentLength((int) file.length()); 
 
 
      
    // read and write file 
    ServletOutputStream op = response.getOutputStream(); 
    // 128 KB buffer 
    int bufferSize = 131072; 
    FileInputStream fileInputStream = new FileInputStream(file); 
    FileChannel fileChannel = fileInputStream.getChannel(); 
    // 6x128 KB = 768KB byte buffer 
    ByteBuffer bb = ByteBuffer.allocateDirect(786432); 
    byte[] barray = new byte[bufferSize]; 
    int nRead, nGet; 
 
    try { 
      while ((nRead = fileChannel.read(bb)) != -1) { 
        if (nRead == 0) 
          continue; 
        bb.position(0); 
        bb.limit(nRead); 
        while (bb.hasRemaining()) { 
          nGet = Math.min(bb.remaining(), bufferSize); 
          // read bytes from disk 
          bb.get(barray, 0, nGet); 
          // write bytes to output 
          op.write(barray); 
        } 
        bb.clear(); 
      } 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } finally { 
      bb.clear(); 
      fileChannel.close(); 
      fileInputStream.close(); 
    } 
  } 
  

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10909.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论