Javaでzip

JavaでZipを展開して書き出すプログラム。以前も作ったことがあったような気がします。java.util.zipパッケージはパスワードつきの、encrypt, decryptに対応していないようなので、winzipaes – Encrypt+Decrypt files in WinZip AES format via java – Google Project Hosting: http://code.google.com/p/winzipaes/とかを使った方がいいのかもしれません。

package org.sssg.soft.sample.zip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
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.ZipException;
import java.util.zip.ZipFile;

public class Tool {
  public static void main(String[] args) {
    Tool app = new Tool();
     if (args.length <= 0) {
     System.out.println("help: java org.sssg.soft.sample.zip.Tool <fileName>");
     return;
     }
     String fileName = args[0];
    try {
      File file = new File(fileName);
      app.unzip(file);
    } catch (ZipException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
    }
  }

  private String getBaseDirName(String s) {
    int exindex = s.lastIndexOf(".");
    return s.substring(0, exindex);
  }

  private File baseDir = null;
  private ZipFile zipFile = null;

  public void unzip(File file) throws ZipException, IOException {
    baseDir = new File(getBaseDirName(file.getAbsolutePath()));
    if (!baseDir.exists()) {
      baseDir.mkdir();
    }
    try {
      zipFile = new ZipFile(file);
      for (Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries
          .hasMoreElements();) {
        ZipEntry ze = entries.nextElement();
        execUnit(ze);
      }
    } finally {
      if (zipFile != null) {
        zipFile.close();
      }
    }
  }

  private void execUnit(ZipEntry ze) throws IOException {
    File outFile = new File(baseDir, ze.getName());
    if (ze.isDirectory()) {
      outFile.mkdirs();
    } else {
      BufferedOutputStream bos = null;
      try {
        bos = new BufferedOutputStream(new FileOutputStream(outFile));
        execFile(ze, bos);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } finally {
        if (bos != null) {
          bos.close();
        }
      }
    }
  }

  private void execFile(ZipEntry ze, BufferedOutputStream bos) throws IOException {
    BufferedInputStream bis = null;
    try {
      InputStream is = zipFile.getInputStream(ze);
      bis = new BufferedInputStream(is);
      int length;
      while ((length = bis.available()) > 0) {
        byte[] bs = new byte[length];
        bis.read(bs);
        bos.write(bs);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (bis != null) {
        bis.close();
      }
    }
  }
}
同じタグの記事: Java
同じタグの記事: Zip
同じカテゴリの記事: Java
関連書籍: Java