4

コンテンツが byte[] として表示される zip ファイルがありますが、元のファイル オブジェクトにアクセスできません。それぞれのエントリーの内容を読みたい。バイトの ByteArrayInputStream から ZipInputStream を作成でき、エントリとその名前を読み取ることができます。ただし、各エントリの内容を抽出する簡単な方法がわかりません。

(私は Apache Commons を見てきましたが、簡単な方法もわかりません)。

更新@Richのコードは問題を解決しているようです、ありがとう

QUERY両方の例の乗数が * 4 (128/512 および 1024*4) であるのはなぜですか?

4

3 に答える 3

6

ストリームからネストされた zip エントリを処理する場合は、アイデアについてこの回答を参照してください。内部エントリは順番にリストされるため、各エントリのサイズを取得し、ストリームからそのバイト数を読み取ることで処理できます。

各エントリを標準出力にコピーする例で更新:

ZipInputStream is;//obtained earlier

ZipEntry entry = is.getNextEntry();

while(entry != null) {
    copyStream(is, out, entry);

    entry = is.getNextEntry();
}
...

private static void copyStream(InputStream in, OutputStream out,
        ZipEntry entry) throws IOException {
    byte[] buffer = new byte[1024 * 4];
    long count = 0;
    int n = 0;
    long size = entry.getSize();
    while (-1 != (n = in.read(buffer)) && count < size) {
        out.write(buffer, 0, n);
        count += n;
    }
}
于 2009-10-07T18:20:47.233 に答える
0

次のZipEntryの開始を計算するのは少し注意が必要です。JDK6に含まれているこの例を参照してください。

public static void main(String[] args) {
    try {
        ZipInputStream is = new ZipInputStream(System.in);
        ZipEntry ze;
        byte[] buf = new byte[128];
        int len;

        while ((ze = is.getNextEntry()) != null) {
            System.out.println("----------- " + ze);

            // Determine the number of bytes to skip and skip them.
            int skip = (int)ze.getSize() - 128;
            while (skip > 0) {
                skip -= is.skip(Math.min(skip, 512));
            }

            // Read the remaining bytes and if it's printable, print them.
            out: while ((len = is.read(buf)) >= 0) {
                for (int i=0; i<len; i++) {
                    if ((buf[i]&0xFF) >= 0x80) {
                        System.out.println("**** UNPRINTABLE ****");

                        // This isn't really necessary since getNextEntry()
                        // automatically calls it.
                        is.closeEntry();

                        // Get the next zip entry.
                        break out;
                    }
                }
                System.out.write(buf, 0, len);
            }
        }
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
于 2009-10-07T19:15:23.080 に答える
0

実際には を として使用しますZipInputStream(InputStreamただし、各エントリの最後で閉じないでください)。

于 2009-10-07T18:26:01.667 に答える