快速java输入\输出流

时间:2012-04-30 11:23:54

标签: java inputstream outputstream java-io

我有一个servlet,它使用响应输出流

将pdf文件复制到客户端
private boolean copyStreamToStream(InputStream in, OutputStream target) {

    logger.info("start copy file to stream");
    try {

        byte[] buffer = new byte[1024 * 8];
        int len = in.read(buffer);
        while (len != -1) {
            target.write(buffer, 0, len);
            len = in.read(buffer);
        }
        in.close();
        target.flush();
        target.close();
        logger.info("end copy file to stream");

    } catch (Exception ex) {

        logger.error("Error: ", ex);
        return false;
    }
    return true;

}

磁盘上pdf文件的InputStream和response.getOutputStream()的OutputStream

问题是PDF文件是一个大文件,需要很长时间才能在客户端加载它有没有办法加快它?

1 个答案:

答案 0 :(得分:1)

发送文件以供下载,而不是将其作为直接响应对象传回。

// Set the headers.
response.setContentType("application/x-download");
response.setHeader("Content-Disposition", "attachment; filename=" + filename);

// Send the file for download.
OutputStream out = response.getOutputStream(  );

编辑。