java NIO 实现FileServlet

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

java代码

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

标签: 代码

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:AES C#, Java, PHP, Python和Javascript几种语言的AES加密解密实现

下一篇:java 简单的H2数据库工具类