java - 无法在 Java/Groovy 中创建 zip 文件

标签 java groovy io zip

我尝试了多种方法在 Java/Groovy 中创建此 zip 文件。我尝试的前几种方法(来自各种博客/帖子)导致 zip 文件损坏且无法打开。所以,我尝试了这个(如下),看起来相当有前途。 sysouts 报告传递给 FileInputStream 的有效文件路径。我不确定是否是传递给 ZipOutputStream 的 FQ 路径导致了问题。不管怎样,下面是代码,它会创建一个小的 (188kb) zip 文件(没有条目)。有什么建议吗?

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

class FileZipper {

    public static void makeZip(Set fullyQualifiedFileNames, String zipFileName, String outDir) throws IOException, FileNotFoundException
    {
        // These are the files to include in the ZIP file
        Object[] filenames = fullyQualifiedFileNames.toArray();
        String fileSeparator =  (String) System.getProperties().get("file.separator");

        // Create a buffer for reading the files
        byte[] buf = new byte[1024];

        // Create the ZIP file
        String outFilename = outDir + fileSeparator +zipFileName;
        FileOutputStream fos = new FileOutputStream(outFilename);
        ZipOutputStream zos = new ZipOutputStream(fos);
        System.out.println("Zipping to file " +outFilename);
        // Compress the files

        for (Object fileName: filenames)
        {
            System.out.println("Adding file: " + fileName);
            FileInputStream fis = new FileInputStream((String)fileName);

            // Add ZIP entry to output stream.
            String[] nodes = ((String)fileName).split("[/[\\\\]]");
            String zipEntry = nodes[nodes.length-1];
            System.out.println("Adding Zip Entry: " + zipEntry);
            zos.putNextEntry(new ZipEntry((String)fileName));

            // Transfer bytes from the file to the ZIP file
            int len;
            int totalBytes = 0;
            while ((len = fis.read(buf)) > 0) 
            {
                totalBytes += len;
                zos.write(buf, 0, len);
            }
            System.out.println("Zipped " +totalBytes +" bytes");
            // Complete the entry
            zos.closeEntry();
            fis.close();
        }

        // Complete the ZIP file
        zos.close();
        fos.close();
    }
}

最佳答案

如果您使用 Groovy,最简单的方法是使用 AntBuilder:

new AntBuilder().zip(
   destfile: "myfile.zip",
   basedir: "baseDir")

或者从 Groovy 1.8 开始:

ant.zip(destfile: 'file.zip', basedir: 'src_dir')

关于java - 无法在 Java/Groovy 中创建 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11476641/

相关文章:

intellij-idea - 无法从 IntelliJ 中的 Gradle 脚本解决 groovy 文件

java - 从字符串数组构建 <String, List<List>> 标记的 Groovy 方法

java - 如何在 eclipse 中调试 groovy 代码 (Play-Framework)

c# - 确定文件移动的目标是否在 C# 中的同一文件系统上

未读取 C++ 文件?

java - 在 joda time 中创建自定义日历

java - IntelliJ 中缺少架构定义

Java递归洪水填充算法的问题

java - 如何hook到java静态方法?

c - 如何在带有 GCC 的 C 程序中的函数之间暂停?