Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从java servlet下载时文件损坏_Java_Servlets - Fatal编程技术网

从java servlet下载时文件损坏

从java servlet下载时文件损坏,java,servlets,Java,Servlets,我在servlet中有一个进程,它创建一个.pdf文件并将其发送给客户端。但是,Adobe不会打开下载的文件(“打开此文档时出错。文件已损坏,无法修复。”)。驻留在服务器上的原始创建的文件很好,Adobe在打开它时没有问题 我的代码: private static void sendFile(HttpServletResponse response, String pdfPath) throws FileNotFoundException, IOException { PrintWrit

我在servlet中有一个进程,它创建一个.pdf文件并将其发送给客户端。但是,Adobe不会打开下载的文件(“打开此文档时出错。文件已损坏,无法修复。”)。驻留在服务器上的原始创建的文件很好,Adobe在打开它时没有问题

我的代码:

private static void sendFile(HttpServletResponse response, String pdfPath) throws FileNotFoundException, IOException {
    PrintWriter out = response.getWriter();
    File f = new File(pdfPath);

    response.setHeader("Content-Transfer-Encoding", "binary");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + f.getName());
    response.setContentLength((int) f.length());

    response.setContentType("application/pdf");

    FileInputStream fileInputStream = new FileInputStream(pdfPath);

    int i;
    while ((i = fileInputStream.read()) != -1) {
        out.write(i);
    }
    fileInputStream.close();
    out.close();
}

写入程序写入的是字符,而不是字节

使用响应输出流


不要一个字节一个字节地读写,尤其是从
文件输入流
中。这是非常低效的。只需使用。

编写器编写的是字符,而不是字节

使用响应输出流


不要一个字节一个字节地读写,尤其是从
文件输入流
中。这是非常低效的。只需使用。

这就是问题所在,感谢您提供的文件.copy()信息。这就是问题所在,感谢您提供的文件.copy()信息。注意:您的内容配置文件名有一个开头双引号,但没有结尾双引号。@VGR很好。谢谢。注意:您的内容配置文件名有一个开头双引号,但没有结尾双引号。@VGR很好。非常感谢。