【发布时间】:2016-07-15 19:35:43
【问题描述】:
我想将普通文件压缩为 .zip,然后将其压缩为 gzip 文件而不创建新文件。
例如假设我有一个pdf文档doc.pdf,我要得到的是:doc.pdf.zip.gz
我不想创建一个名为doc.pdf.zip 的新文件,然后打开它并压缩它。
我正在使用服务器从浏览器中获取文件并将其返回,这是我的功能:
public void ZIPandGZIP(String fileName, OutputStream os, String header) throws FileNotFoundException
{
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
DataOutputStream dos = new DataOutputStream(os);
try {
dos.writeBytes(header);
ZipOutputStream zpos = new ZipOutputStream(os);
zpos.putNextEntry(new ZipEntry(fileName));
GZIPOutputStream gos = (new GZIPOutputStream(zpos));
fis.read(data);
gos.write(data);
zpos.flush();
zpos.close();
gos.flush();
gos.close();
dos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我得到一个文件doc.pdf.zip.gz,但它有一个损坏的文件doc.pdf,为什么没有压缩??
【问题讨论】:
-
将
close()调用移动到finally块 -
谢谢,我这样做了,但它总是返回相同的结果。
-
与您的问题无关,只是最佳实践:P
-
只是想知道,为什么?为什么要压缩两次?
标签: java server zip gzipoutputstream