java - 如何在java中压缩一组给定的文件
问题描述
给定一组文件的位置,我想压缩一组文件。
将该 Zip 文件发送到下面提到的方法
private StreamingOutput buildStreamingOutput(final File pdfFile, final boolean isGeneratedPdf) {
return new StreamingOutput() {
@Override
public void write(OutputStream output) throws IOException, WebApplicationException {
java.nio.file.Path path = Paths.get(pdfFile.getAbsolutePath());
byte[] data = CryptoUtil.decryptAsByteArray(path);
output.write(data);
output.flush();
output.close();
if (isGeneratedPdf) {
pdfFile.delete();
}
}
};
}
是否可以压缩文件并将该 Zip 文件作为文件(File.class)发送
解决方案
愿对你有用。
使用下面的代码:
public void buildStreamingOutput(HttpServletResponse
resp,java.util.List<File> files) throws IOException {
ZipOutputStream zipOutstream = new
ZipOutputStream(resp.getOutputStream());
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment; filename=
{zipfilename.zip}");
for(File file : files) {
appendFileToZIP(zipOutstream,file);
}
}
public void appendFileToZIP( ZipOutputStream _zipOutstream ,final File pdfFile) {
int nlength = 0;
FileInputStream fis = null;
DataInputStream disObj = null;
try {
if (!pdfFile.exists()) {
System.out.println(" file does not exists "+pdfFile.getName());
return;
}
fis = new FileInputStream(pdfFile);
_zipOutstream.putNextEntry(new ZipEntry(pdfFile.getName()));
disObj = new DataInputStream(fis);
byte[] bbuf = new byte[1024];
while ((disObj != null) && ((nlength = disObj.read(bbuf)) != -1)) {
_zipOutstream.write(bbuf, 0, nlength);
}
_zipOutstream.flush();
} catch (IOException e) {
} catch (Exception e) {
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
}
推荐阅读
- mysql - Tstamp 间隔总是从午夜开始
- multithreading - MDC 上下文仅被复制到 ForkJoinPool 的一个线程
- python-3.x - DDPG - Actor Critic Network 不与连续动作空间收敛
- node.js - 在 NodeJs 中处理工作进程的响应
- python - AttributeError:“Cal”对象没有属性“area”
- google-app-maker - 谷歌应用程序制造商:如何列出现有组?
- java - 如何确定列表中是否有提供总和的 2 个元素?
- python - 如何将 Lambda 层作为输入层添加到 Keras 中的现有模型中?
- python - 在 matplotlib 中使用数组制作滑块
- linux - X86_64 汇编代码段错误并给出堆栈粉碎错误