java - 使用 util.zip 压缩文件 无目录

标签 java zip

我有以下情况: 我可以使用以下方法压缩我的文件:

public boolean generateZip(){
    byte[] application = new byte[100000];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // These are the files to include in the ZIP file
    String[] filenames = new String[]{"/subdirectory/index.html", "/subdirectory/webindex.html"};

    // Create a buffer for reading the files

    try {
        // Create the ZIP file

        ZipOutputStream out = new ZipOutputStream(baos);

        // Compress the files
        for (int i=0; i<filenames.length; i++) {
            byte[] filedata  = VirtualFile.fromRelativePath(filenames[i]).content();
            ByteArrayInputStream in = new ByteArrayInputStream(filedata);

            // Add ZIP entry to output stream.
            out.putNextEntry(new ZipEntry(filenames[i]));

            // Transfer bytes from the file to the ZIP file
            int len;
            while ((len = in.read(application)) > 0) {
                out.write(application, 0, len);
            }

            // Complete the entry
            out.closeEntry();
            in.close();
        }

        // Complete the ZIP file
        out.close();
    } catch (IOException e) {
        System.out.println("There was an error generating ZIP.");
        e.printStackTrace();
    }
    downloadzip(baos.toByteArray());
}

这工作得很好,我可以下载 xy.zip,其中包含以下目录和文件结构:
子目录/
----index.html
----webindex.html

我的目标是完全省略子目录,并且 zip 应该只包含这两个文件。有什么办法可以实现这一点吗? (我在 Google App Engine 上使用 Java)。

提前致谢

最佳答案

如果您确定在省略目录的情况下 filenames 数组中包含的文件是唯一的,请更改用于构造 ZipEntry 的行:

String zipEntryName = new File(filenames[i]).getName();
out.putNextEntry(new ZipEntry(zipEntryName));

这使用 java.io.File#getName()

关于java - 使用 util.zip 压缩文件 无目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11298529/

相关文章:

java - 如何检查字符串是否为日期?

java - 如何提取文件 jre-9/lib/modules?

objective-c - 如何在不使用任何外部库的情况下压缩文件?

ruby - 为什么 Ruby 在做同样的事情时有 zip 和 transpose?

Java:多态性和调用方法

java - 按列显示数组

java - Clojure:交叉引用变量、声明和编译错误

c# - mimetype 文件有一个长度为 n 的额外字段。 mimetype 文件不允许使用 ZIP 格式的额外字段功能

android - 将压缩数据库复制/解压缩到 Android 时出现 SQLiteException

用于解压缩文件的 VBA 脚本 - 它只是创建空文件夹