2011-04-08 16 views
3

這是將PDF文件輸出到瀏覽器的一段代碼,它可以更快嗎?
這是在Java servlet中實現的。有更快的方式輸出PDF文件嗎?

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

爲什麼你寫的一個直接'ByteArrayOutputStream'而不是響應的OutputStream的? 1M的緩衝區可能不會提高網絡的性能。 – 2011-04-08 07:03:44

回答

5

使用Google Guava您可以在一個行總結一下:

import com.google.common.io.Files; 

private OutputStream getOutputStream(File file) throws IOException { 
    return Files.newOutputStreamSupplier(file).getOutput(); 
} 
+0

這可能是迄今爲止我讀過的最好的答案,因爲它封裝了經過良好測試的代碼中緩衝輸入流的讀取。 – 2011-05-04 16:35:15

+2

@Dataknife:請注意,問題中的代碼非常具有誤導性。 OP基本上要求以最快的方式將PDF文件寫入servlet響應,而不是獲取PDF文件的OutputStream的最快方式。 – BalusC 2011-05-04 16:49:31

+0

@BelusC:我同意,但即使他的代碼沒有任何引用servlet或等效。所以,我們假設這是關於從文件中獲取流的。請評論這個,如果我錯了。 – 2011-05-04 17:19:05

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