9

を実行できますがZipInputStream、反復を開始する前に、反復中に必要な特定のファイルを取得したいと考えています。どうやってやるの?

ZipInputStream zin = new ZipInputStream(myInputStream)
while ((entry = zin.getNextEntry()) != null)
 {
    println entry.getName()
}
4

3 に答える 3

6

ZipEntry で getName() メソッドを使用して、必要なファイルを取得します。

ZipInputStream zin = new ZipInputStream(myInputStream)
String myFile = "foo.txt";
while ((entry = zin.getNextEntry()) != null)
{
    if (entry.getName().equals(myFileName)) {
        // process your file
        // stop looking for your file - you've already found it
        break;
    }
}

Java 7 以降では、1 つのファイルのみが必要で、読み取るファイルがある場合は、ZipStream の代わりに ZipFile を使用することをお勧めします。

ZipFile zfile = new ZipFile(aFile);
String myFile = "foo.txt";
ZipEntry entry = zfile.getEntry(myFile);
if (entry) {
     // process your file           
}
于 2015-04-08T13:07:32.387 に答える
6

作業しmyInputStreamている がディスク上の実際のファイルから取得されたものである場合java.util.zip.ZipFileは、代わりに単純に使用できます。これは、 によってサポートされ、RandomAccessFile名前による zip エントリへの直接アクセスを提供します。しかし、あなたが持っているのがInputStream.

ストリームを一時ファイルにコピーし、 を使用してそのファイルを開くことができますZipFile。または、事前にデータの最大サイズがわかっている場合 (たとえば、前もって宣言する HTTP 要求のContent-Length場合) を使用してBufferedInputStream、必要なエントリが見つかりました。

BufferedInputStream bufIn = new BufferedInputStream(myInputStream);
bufIn.mark(contentLength);
ZipInputStream zipIn = new ZipInputStream(bufIn);
boolean foundSpecial = false;
while ((entry = zin.getNextEntry()) != null) {
  if("special.txt".equals(entry.getName())) {
    // do whatever you need with the special entry
    foundSpecial = true;
    break;
  }
}

if(foundSpecial) {
  // rewind
  bufIn.reset();
  zipIn = new ZipInputStream(bufIn);
  // ....
}

(私はこのコードを自分でテストしていません。巻き戻す前に、最初の zip ストリームを閉じずに最初の zip ストリームを閉じることができるようにするために、と最初の のCloseShieldInputStream間にcommons-io のようなものを使用する必要があるかもしれません)。bufInzipInbufIn

于 2015-04-08T14:10:54.020 に答える
2

Finding a file in zip entry を見てください

ZipFile file = new ZipFile("file.zip");
ZipInputStream zis = searchImage("foo.png", file);

public searchImage(String name, ZipFile file)
{
  for (ZipEntry e : file.entries){
    if (e.getName().endsWith(name)){
      return file.getInputStream(e);
    }
  }

  return null;
}
于 2015-04-08T13:07:20.390 に答える