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 をダウンロードできます:
subdirectory/
----index.html
----webindex.html

私の目的は、サブディレクトリを完全に除外することであり、zip には 2 つのファイルのみが含まれている必要があります。これを達成する方法はありますか?(Google App Engine で Java を使用しています)。

前もって感謝します

4

3 に答える 3

3

ディレクトリを省略した場合に配列に含まれるファイルが一意であることが確実な場合は、 sfilenamesを構築するための行を変更します。ZipEntry

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 に答える