スキップしてメイン コンテンツに移動

JavaでDirectoryをZIP圧縮・解凍

JavaでDirectoryをZIP圧縮するためのソースコード

private static final int _4K_BYTES = 4096;

// core part... piece of cake....
public final static void zipDirecory(File dir, File zipFile) throws IOException {
  if (!dir.isDirectory()) {
      throw new IllegalArgumentException("Not directory :" + dir);
  }
  try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile))) {
      File parentFile = dir.getParentFile();
      Path baPath = parentFile == null ? dir.toPath() : parentFile.toPath();
      zipDirectory(dir, new byte[_4K_BYTES], out, baPath);
  }
}

private static void zipDirectory(File dir, byte[] bs, ZipOutputStream out, Path basePath) throws IOException {
  for (File f : dir.listFiles()) {
    if (f.isDirectory()) {
      zipDirectory(f, bs, out, basePath);
    }
    else {
      out.putNextEntry(new ZipEntry(basePath.relativize(f.toPath()).toFile().getPath()));
      copy(new FileInputStream(f), out, bs);
    }
 }
}

// trivial helper methods... please use java commons library etc... if you want...
private final static void copy(InputStream is, OutputStream os, byte[] buffer)throws IOException
{
 try{
  for (int bytes = 0 ;(bytes = is.read(buffer)) != -1; ) 
  {
   os.write(buffer, 0, bytes);
  }
 }finally{
  close(is);
 }
}

public final static void close(Closeable closeable){
 if(closeable != null){
  try{
   closeable.close();
  }
  catch (IOException e) {
   e.printStackTrace();
  }
 }
}

JavaでZipファイルを解凍するためのコード

    public final static Map unzipOnMemory(InputStream is) throws IOException{
        Map files = new HashMap();
        byte[] buffer = new byte[_1K_BYTES];
        ZipInputStream zis = null;
        try{
            zis = new ZipInputStream(new BufferedInputStream(is));
            for(ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry()) {
                
                // you can change the code, like save unzipped files on disk etc,
                files.put(entry.getName(), toBytesNoClose(zis, buffer));
            }
        }
        finally{
            // simply close - you can use Closeables class in Guava Library
            closeQuietly(zis);
        }
        return files;
    }
    
    public final static byte[] toBytesNoClose(InputStream in, byte[] buffer) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        for (int bytes = 0 ;(bytes = in.read(buffer)) != -1; ) 
        {
            baos.write(buffer, 0, bytes);
        }
        baos.flush();
        return baos.toByteArray();
    }

JavaのZipライブラリ

OracleのJDKに付属している標準のJavaライブラリでは、どうもパスワード保護されたファイルは解凍できないようなので(しっかりと確認した訳ではないので間違っていたらごめんなさい!)、3rd party製のライブラリを使用するのがよいようです。
ライブラリとして以下の2つを見つけました。

コメント