java
java - zip, unzip
고.니
2019. 2. 18. 23:30
반응형
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import com.google.common.collect.Lists; public class ZipUtil { public static void zip(String zipFileName, List<File> files) throws IOException { byte[] buf = new byte[1024]; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { for (int i = 0; i < files.size(); i++) { FileInputStream in = new FileInputStream(files.get(i)); try { String fileName = files.get(i).getAbsolutePath(); ZipEntry ze = new ZipEntry(fileName); out.putNextEntry(ze); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); } finally { in.close(); } } } finally { if (out != null) { out.close(); } } } public static List<String> unzip(String zipFilePath, String destDir) throws IOException { File dir = new File(destDir); if (!dir.exists()) { dir.mkdirs(); } byte[] buffer = new byte[1024]; FileInputStream fis = null; ZipInputStream zis = null; ZipEntry ze = null; List<String> fileList = Lists.newArrayList(); try { fis = new FileInputStream(zipFilePath); zis = new ZipInputStream(fis); ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); File newFile = new File(destDir + File.separator + fileName); fileList.add(fileName); if (ze.isDirectory()) { newFile.mkdirs(); } else { FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } zis.closeEntry(); ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } finally { if (fis != null) { fis.close(); } } return fileList; } } |
반응형