如何创建多个图像文件的zip文件

时间:2013-05-14 15:19:46

标签: java file zip fileinputstream zipoutputstream

我正在尝试创建多个图像文件的zip文件。我已成功创建所有图像的zip文件,但不知何故所有图像都被挂起到950字节。我不知道这里出了什么问题,现在我无法打开将图像压缩成该zip文件。

这是我的代码。谁能让我知道这里发生了什么?

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();

2 个答案:

答案 0 :(得分:16)

这是我一直用于任何文件结构的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;
}

答案 1 :(得分:10)

改变这个:

while((length=fin.read())>0)

到此:

while((length=fin.read(b, 0, 1024))>0)

并将缓冲区大小设置为1024字节:

b=new byte[1024];