这种 zip 方法有什么问题吗?
我有一个方法可以压缩 5 个文件。它生成一个 zip 文件,没有错误,但我无法打开它来检查内容。我尝试通过电子邮件发送它,但 gmail 说它无法发送损坏的文件。尝试在 Windows 中使用 WinRAR 打开会出现错误:
存档格式未知或已损坏
这是方法:
private void zipTestFiles() throws FileNotFoundException, IOException
{
File[] filenames = fileDir.listFiles(fileNameFilter(Constants.PAGE_MON_FILENAME_FILTER));
byte[] buf = new byte[1024];
String outFilename = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separatorChar + Constants.PAGEMONITOR_ZIP;
DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(outFilename)));
for (int i=0; i<filenames.length; i++)
{
FileInputStream in = new FileInputStream(filenames[i]);
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
}
out.close();
}
I have a method which zips up 5 files. It produces a zip file without error, but I cannot open it to examine the contents. I tried emailing it and gmail said it cannot send corrupt files. Trying to open with WinRAR in Windows results in an error stating:
The archive is either in unknown format or damaged
This is the method:
private void zipTestFiles() throws FileNotFoundException, IOException
{
File[] filenames = fileDir.listFiles(fileNameFilter(Constants.PAGE_MON_FILENAME_FILTER));
byte[] buf = new byte[1024];
String outFilename = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separatorChar + Constants.PAGEMONITOR_ZIP;
DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(outFilename)));
for (int i=0; i<filenames.length; i++)
{
FileInputStream in = new FileInputStream(filenames[i]);
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
}
out.close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 ZipOutputStream 而不是 DeflaterOutputStream。并且不要忘记创建条目。在编写实现之前,请阅读 ZipOutputStream 的 javadoc。
You should use
ZipOutputStream
instead ofDeflaterOutputStream
. And do not forget to create entries. Read javadoc ofZipOutputStream
before writing the implementation.尝试使用 Java 中已经存在的 ZipOutputStream。 DeflaterOutputStream 仅使用 DEFLATE 方法进行压缩,但不会自动放入 ZIP 标头。
Try with ZipOutputStream which already exists in Java. DeflaterOutputStream only uses DEFLATE method to compress but doesn't put ZIP headers automatically.