java - 如何创建包含多个图像文件的 zip 文件

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

最佳答案

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

关于java - 如何创建包含多个图像文件的 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16546992/

相关文章:

eclipse - Ant构建类路径jar生成 "error in opening zip file"

java - JDBC DatabaseMetaData.getColumns() 返回重复列

java - 发现来自另一个数据中心的节点

java - Spring Boot 管理页面

java - 我收到 IllegalStateException : Already connected and I cannot figure out why

html - 克隆 CSS 样式的文件上传按钮

php - 如何在php中按文件大小对 ListView 进行排序

c - c - 如何在c中比fprintf更快地写入文本文件?

php - 将文件添加到存档后删除文件会阻止创建存档

java - 如何打开 zip 文件并遍历 Android 上的每个压缩文件?