Java 如何创建多个图像文件的 zip 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16546992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a zip file of multiple image files
提问by Vighanesh Gursale
I am trying to create a zip file of multiple image files. I have succeeded in creating the zip file of all the images but somehow all the images have been hanged to 950 bytes. I don't know whats going wrong here and now I can't open the images were compressed into that zip file.
我正在尝试创建一个包含多个图像文件的 zip 文件。我已经成功地创建了所有图像的 zip 文件,但不知何故所有图像都被挂到了 950 字节。我不知道这里出了什么问题,现在我无法打开压缩到该 zip 文件中的图像。
Here is my code. Can anyone let me know what's going here?
这是我的代码。谁能让我知道这里发生了什么?
String path="c:\windows\twain32";
File f=new File(path);
f.mkdir();
File x=new File("e:\test");
x.mkdir();
byte []b;
String zipFile="e:\test\test.zip";
FileOutputStream fout=new FileOutputStream(zipFile);
ZipOutputStream zout=new ZipOutputStream(new BufferedOutputStream(fout));
File []s=f.listFiles();
for(int i=0;i<s.length;i++)
{
b=new byte[(int)s[i].length()];
FileInputStream fin=new FileInputStream(s[i]);
zout.putNextEntry(new ZipEntry(s[i].getName()));
int length;
while((length=fin.read())>0)
{
zout.write(b,0,length);
}
zout.closeEntry();
fin.close();
}
zout.close();
采纳答案by hoaz
Change this:
改变这个:
while((length=fin.read())>0)
to this:
对此:
while((length=fin.read(b, 0, 1024))>0)
And set buffer size to 1024 bytes:
并将缓冲区大小设置为 1024 字节:
b=new byte[1024];
回答by salocinx
This is my zip function I always use for any file structures:
这是我的 zip 函数,我总是用于任何文件结构:
public static File zip(List<File> files, String filename) {
File zipfile = new File(filename);
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
// compress the files
for(int i=0; i<files.size(); i++) {
FileInputStream in = new FileInputStream(files.get(i).getCanonicalName());
// add ZIP entry to output stream
out.putNextEntry(new ZipEntry(files.get(i).getName()));
// transfer bytes from the file to the ZIP file
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// complete the entry
out.closeEntry();
in.close();
}
// complete the ZIP file
out.close();
return zipfile;
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
return null;
}