0

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

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)。

提前致谢

4

3 回答 3

3

如果您确定filenames数组中包含的文件是唯一的(如果您省略了目录),请更改构造ZipEntrys 的行:

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

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

于 2012-07-02T17:50:09.213 回答
1

您可以使用Apache Commons io列出所有文件,然后将它们读取到InputStream

替换下面的行

String[] filenames = new String[]{"/subdirectory/index.html", "/subdirectory/webindex.html"}

与以下

    Collection<File> files = FileUtils.listFiles(new File("/subdirectory"), new String[]{"html"}, true);
    for (File file : files)
    {
        FileInputStream fileStream = new FileInputStream(file);
        byte[] filedata = IOUtils.toByteArray(fileStream);
        //From here you can proceed with your zipping.
    }

如果您有问题,请告诉我。

于 2012-07-02T17:55:11.720 回答
0

您可以使用该isDirectory()方法VirtualFile

于 2012-07-02T17:51:01.443 回答