用于文件下载的异步Servlet-首选实现

时间:2019-02-11 06:55:41

标签: java file asynchronous servlets

最近,在研究Servlet中的异步处理期间,我有两种下载文件的方式。但是我不知道哪个更好。

第一个:首先读取文件,然后开始写入

private void writeFile1(File f, ServletRequest req) throws IOException {
    AsynchronousFileChannel fileChannel = createMyFileChannel(f);
    ByteBuffer buffer = ByteBuffer.allocate((int)f.length());

    final AsyncContext ctx = req.startAsync();
    //ctx.addListener(...);

    fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            ctx.start(() -> {
                try {
                    byte[] bt = attachment.array();
                    HttpServletResponse res = (HttpServletResponse)ctx.getResponse();
                    res.getOutputStream().write(bt);
                    // ...
                }
                catch (IOException e) {
                    // ...
                }
                finally {
                    ctx.complete();
                }
            });
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {}
    });
}

第二次:首先开始写入,然后读取文件

    private void writeFile2(File f, ServletRequest req) throws IOException {
    AsynchronousFileChannel fileChannel = createMyFileChannel(f);
    ByteBuffer buffer = ByteBuffer.allocate((int)f.length());

    final AsyncContext ctx = req.startAsync();
    //ctx.addListener(...);

    ctx.start(() -> {
        HttpServletResponse res = (HttpServletResponse)ctx.getResponse();
        fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                try {
                    byte[] bt = attachment.array();
                    res.getOutputStream().write(bt);
                    //...
                }
                catch (IOException e) {
                    // ...
                }
                finally {
                    ctx.complete();
                }
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {}
        });
    });
}

它们都能正常工作,但是哪一个更快? 谢谢您的回答。

0 个答案:

没有答案