【问题标题】:Output PDF files into Zip File using Java and JSP使用 Java 和 JSP 将 PDF 文件输出为 Zip 文件
【发布时间】:2021-04-28 16:16:41
【问题描述】:

我正在尝试通过单击按钮将多个 PDF 文件输出到单个 Zip 文件中。通过单击“下载规格表 Zip 文件”,专门输出所有规格表,每个规格表由一个 PDF 文件组成。附上一张图片来更好地说明这一点。

现在,我的代码设置为将所有 SPEC SHEET 输出到我的本地下载文件夹,作为一种测试(正在运行)。我需要对此进行修改,以便将 SPEC SHEET 输出到单个 Zip 文件中。

这是我的代码:

    public void addToZipFile(String fileUrl, ZipOutputStream zos, eclUser user) throws FileNotFoundException, IOException {
    URL u = new URL(fileUrl);
    URLConnection uc = u.openConnection();
    String contentType = uc.getContentType();
    int contentLength = uc.getContentLength();
    if (contentType.startsWith("text/") || contentLength == -1) {
      throw new IOException("This is not a binary file.");
    }
    InputStream raw = uc.getInputStream();
    InputStream in = new BufferedInputStream(raw);
    byte[] data = new byte[contentLength];
    int bytesRead = 0;
    int offset = 0;
    while (offset < contentLength) {
      bytesRead = in.read(data, offset, data.length - offset);
      if (bytesRead == -1)
        break;
      offset += bytesRead;
    }
    in.close();

    if (offset != contentLength) {
      throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
    }

    String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);

    String outputPath = eclSystem.getUserDownloadDir(user) + eclSystem.getDirSep() + fileName;
    String absPath = eclSystem.file2Absolute(outputPath);
    FileOutputStream out = new FileOutputStream(absPath);

    out.write(data);
    out.flush();
    out.close();
}

任何帮助将不胜感激。提前致谢!

【问题讨论】:

    标签: java file-io zip zipfile fileoutputstream


    【解决方案1】:

    查看 java.util.zip 包 (https://docs.oracle.com/javase/7/docs/api/java/util/zip/package-summary.html) 或 Apache Commons Compress https://commons.apache.org/proper/commons-compress/zip.html 以获取创建 Zip 文件所需的 Java 类。

    【讨论】:

      猜你喜欢
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 2011-04-21
      相关资源
      最近更新 更多