有更快的方法输出PDF文件吗?

lam*_*988 3 java servlets

这是一段将PDF文件输出到浏览器的代码,它可以更快吗?
这是在Java servlet中实现的.

private ByteArrayOutputStream getByteArrayOutputStreamFromFile(File file) throws Exception {
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new ByteArrayOutputStream();
            byte[] byteContent = new byte[1024 * 1024];
            int len = 0;
            while ((len = bis.read(byteContent)) != -1) {
                bos.write(byteContent, 0, len);
            }
            return bos;
        } catch (Exception ex) {
            throw ex;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Nir*_*ond 5

 response.setContentType("application/pdf");
 ServletContext ctx = getServletContext();
 InputStream is = ctx.getResourceAsStream("/erp.pdf");

 int read =0;
 byte[] bytes = new byte[1024];
 OutputStream os = response.getOutputStream();
 while((read = is.read(bytes)) != -1)
 {
 os.write(bytes, 0, read);
 }
 os.flush();
 os.close();
Run Code Online (Sandbox Code Playgroud)


yve*_*lem 5

使用Google Guava,您可以在一行中对此进行汇总:

import com.google.common.io.Files;

private OutputStream getOutputStream(File file) throws IOException {
    return Files.newOutputStreamSupplier(file).getOutput();
}
Run Code Online (Sandbox Code Playgroud)

  • @Dataknife:请注意,问题中的代码非常具有误导性.OP基本上要求以最快的方式将PDF文件写入servlet响应,而不是以最快的方式获取PDF文件的`OutputStream`. (2认同)
  • 要使这个servlet相关,请改为:import com.google.common.io.Files; public void doGet(HttpServletRequest request,HttpServletResponse response)抛出ServletException {Files.copy(File,response.getOutputStream()); 为简洁起见,代码已被省略,但意图应该清楚...... [http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Files.html](番石榴文件) (2认同)