extract Zip Entry - Android File Input Output

Android examples for File Input Output:Zip File

Description

extract Zip Entry

Demo Code


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import android.util.Log;

public class Main {
  private static final String TAG = "";

  public static void extractZipEntry(ZipFile zipFile, String entryName, File destDir) {
    if (zipFile == null || entryName == null || destDir == null)
      return;//w w w.  j ava2  s  . c om

    Log.d(TAG, "zipFile: " + zipFile);
    destDir.getParentFile().mkdirs();
    ZipEntry zE = zipFile.getEntry(entryName);

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    if (entries.hasMoreElements()) {
      ZipEntry nextElement = entries.nextElement();
      // Log.d(TAG, "ze: " + nextElement);
    }

    try {
      InputStream in = null;
      // in = zipFile.getInputStream(zE);
      in = new FileInputStream(new File(zipFile.getName()));
      ZipInputStream zIn = new ZipInputStream(in);
      try {
        ZipEntry ze;
        while ((ze = zIn.getNextEntry()) != null) {
          if (!ze.getName().startsWith(entryName) || ze.isDirectory()) {
            continue;
          }
          Log.d(TAG, "ze: " + ze);
          String name = ze.getName().substring(entryName.length());

          File destFile = new File(destDir, name);
          destFile.getParentFile().mkdirs();
          FileOutputStream fout = new FileOutputStream(destFile);
          byte[] buffer = new byte[1024];
          int count;
          while ((count = zIn.read(buffer)) != -1) {
            fout.write(buffer, 0, count);
          }
          fout.flush();
          fout.close();
        }
      } finally {
        zIn.close();
      }

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Related Tutorials