lamwaiman1988
lamwaiman1988

Reputation: 3742

Is there a faster way to output a PDF file?

This is a piece of code to output a PDF file to browser, could it be faster?
This is implemented in a 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();
            }
        }
    }

Upvotes: 3

Views: 1632

Answers (3)

yves amsellem
yves amsellem

Reputation: 7234

Using Google Guava you can summarize this in one line:

import com.google.common.io.Files;

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

Upvotes: 5

Harry Joy
Harry Joy

Reputation: 59660

A suggestion:

always look to libraries such as Apache Commons FileUtils. They provide simple and easy to use methods.

You can also leave out the BufferedOutputStream as you're already using a buffer. But that's not going to make a big difference. Try using the nio instead of the streams. This might make some difference.

Also look at this: How to download and save a file from Internet using Java? might help you some way.

Upvotes: 0

Nirmal- thInk beYond
Nirmal- thInk beYond

Reputation: 12054

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

Upvotes: 5

Related Questions