2

MyZipFile.zip(1)ファイルMyFile.txtと(2)ファイルを含むフォルダーMyFolderを含むzipファイルがあるとしますMyFileInMyFolder.txt。つまり、次のようなものです。

MyZipFile.zip
   |-> MyFile.txt
   |-> MyFolder
          |->MyFileInMyFolder.txt

このzipアーカイブを解凍したいと思います。私がオンラインで検索して見つけた最も一般的なコードサンプルはZipInputStream、この質問の下部に貼り付けられたコードのようなクラスを使用しています。ただし、これに関する問題は、上記の例を使用するとMyFolder、の内容を作成しますが、解凍しないことですMyFolder。zipアーカイブ内のフォルダの内容を、ZipInputStreamまたは他の方法で解凍できるかどうかを知っている人はいますか?

public static boolean unzip(File sourceZipFile, File targetFolder)
{
 // pre-stuff

 ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(sourceZipFile));
 ZipEntry zipEntry = null;

 while ((zipEntry = zipInputStream.getNextEntry()) != null)
 {
  File zipEntryFile = new File(targetFolder, zipEntry.getName());

  if (zipEntry.isDirectory())
  {
   if (!zipEntryFile.exists() && !zipEntryFile.mkdirs())
    return false;
  }
  else
  {
   FileOutputStream fileOutputStream = new FileOutputStream(zipEntryFile);

   byte buffer[] = new byte[1024];
   int count;

   while ((count = zipInputStream.read(buffer, 0, buffer.length)) != -1)
    fileOutputStream.write(buffer, 0, count); 

   fileOutputStream.flush();
   fileOutputStream.close();
   zipInputStream.closeEntry();
  }
 }

 zipInputStream.close();

 // post-stuff
}
4

1 に答える 1

4

これを試して:

ZipInputStream zis = null;
try {

    zis = new ZipInputStream(new FileInputStream(zipFilePath));
    ZipEntry entry;

    while ((entry = zis.getNextEntry()) != null) {

        // Create a file on HDD in the destinationPath directory
        // destinationPath is a "root" folder, where you want to extract your ZIP file
        File entryFile = new File(destinationPath, entry.getName());
        if (entry.isDirectory()) {

            if (entryFile.exists()) {
                logger.log(Level.WARNING, "Directory {0} already exists!", entryFile);
            } else {
                entryFile.mkdirs();
            }

        } else {

            // Make sure all folders exists (they should, but the safer, the better ;-))
            if (entryFile.getParentFile() != null && !entryFile.getParentFile().exists()) {
                entryFile.getParentFile().mkdirs();
            }

            // Create file on disk...
            if (!entryFile.exists()) {
                entryFile.createNewFile();
            }

            // and rewrite data from stream
            OutputStream os = null;
            try {
                os = new FileOutputStream(entryFile);
                IOUtils.copy(zis, os);
            } finally {
                IOUtils.closeQuietly(os);
            }
        }
    }
} finally {
    IOUtils.closeQuietly(zis);
}

ストリームのコピー/クローズを処理するためにApacheCommonsIOを使用することに注意してください。

于 2012-06-01T13:24:01.067 に答える