这是一段将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)
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)
使用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)
归档时间: |
|
查看次数: |
1240 次 |
最近记录: |