Java tutorial
/** * Copyright 2014 Chnoumis. * * Chnoumis licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package com.chnoumis.commons.zip.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import org.apache.commons.compress.archivers.ArchiveException; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveOutputStream; import org.apache.commons.compress.archivers.ArchiveStreamFactory; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.utils.IOUtils; public class ZipUtils { public static void zip(List<ZipInfo> zipInfos, OutputStream out) throws IOException, ArchiveException { ArchiveOutputStream os = null; try { os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out); for (ZipInfo zipInfo : zipInfos) { os.putArchiveEntry(new ZipArchiveEntry(zipInfo.getFileName())); InputStream o = null; if (zipInfo.getFileContent() != null) { o = new ByteArrayInputStream(zipInfo.getFileContent()); } else { o = zipInfo.getInputStream(); } IOUtils.copy(o, os); os.closeArchiveEntry(); } } finally { if (os != null) { os.close(); } } out.close(); } public static List<ZipInfo> unZiptoZipInfo(InputStream is) throws ArchiveException, IOException { List<ZipInfo> results = new ArrayList<ZipInfo>(); ArchiveInputStream in = null; try { in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { ZipInfo zipInfo = new ZipInfo(); OutputStream o = new ByteArrayOutputStream(); try { IOUtils.copy(in, o); } finally { o.close(); } zipInfo.setFileName(entry.getName()); zipInfo.setFileContent(o.toString().getBytes()); results.add(zipInfo); } } finally { if (in != null) { in.close(); } } is.close(); return results; } public static void unZip(InputStream is) throws ArchiveException, IOException { ArchiveInputStream in = null; try { in = new ArchiveStreamFactory().createArchiveInputStream("zip", is); ZipArchiveEntry entry = null; while ((entry = (ZipArchiveEntry) in.getNextEntry()) != null) { OutputStream o = new FileOutputStream(entry.getName()); try { IOUtils.copy(in, o); } finally { o.close(); } } } finally { if (in != null) { in.close(); } } is.close(); } }