【发布时间】: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