5

概要:を含むバイト イメージがある場合、テキスト ファイルの行を返すクリーンで正しいリーダーを取得するにはどうすればよいですか?a.zipa.txt

Web サービスから .zip ファイルのイメージをダウンロードしますbyte[] content。のようなメソッドを書きたいと思います。

private BufferedReader contentToBufferedReader(byte[] content)

次のように使用できるリーダーを返します

reader = contentToBufferedReader(content);
while ((line = reader.readLine()) != null) {
    processThe(line);
}
reader.close()

これまでのところ、私は(更新しました)

private BufferedReader contentToBufferedReader(byte[] content) {

    ByteArrayInputStream bais = new ByteArrayInputStream(content);
    ZipInputStream zipStream = new ZipInputStream(bais);
    BufferedReader reader = null;

    try {
        ZipEntry entry = zipStream.getNextEntry();

        // I need only the first (and the only) entry from the zip file.
        if (entry != null) {
            reader = new BufferedReader(new InputStreamReader(zipStream, "UTF-8"));
            System.out.println("contentToBufferedReader(): success");
        }
    }
    catch (IOException e) {
        System.out.println("contentToBufferedReader(): failed...");
        System.out.println(e.getMessage());
    }

    return reader;
}

何かが失敗したときにすべてのストリーム オブジェクトを閉じる方法がわかりません。さらに、reader返品、使用、閉鎖に成功した場合、それらを閉鎖する方法がわかりません。

4

2 に答える 2

1

これにより、一度にすべてのバイトが取得されます(便宜上、グアバByteStreamsを使用します)

ZipEntry entry = zipStream.getNextEntry();
while (entry != null) {
  if (!entry.isDirectory()) {
    String filename = entry.getName();//this includes the path!
    byte[] data = ByteStreams.toByteArray(zipStream);
    //do something with the bytes 
  }
  entry = zipIn.getNextEntry();
}

次のようなリーダーを取得できます。

InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(data)));

zipStream.getNextEntry() を呼び出すと、zipStream が進みます。また、ストリームはマークとリセットのiircをサポートしていないと思います。つまり、一度しか読み取れないことを意味します(したがって、ランダムアクセスが必要な可能性のある他の処理に渡す前に、すべてを一度に取得します)

于 2013-10-08T11:06:49.963 に答える