将zip文件提取到目录中,如果目标文件不存在,则会创建该文件。
/** from nowjava - 时代Java**/ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class Main{//来 自 时代Java - N o w J a v a . c o m /** * Size of the buffer to read/write data */ private static final int BUFFER_SIZE = 4096; /** * Extracts zip file into a directory, if destination file is not exist, it will create it then. * * @param zipFile file to be unzip * @param destDirectory folders to save unziped files * @throws IOException */ public static boolean unzip(File zipFile, String destDirectory) { ZipInputStream zipIn = null; try { zipIn = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry entry = zipIn.getNextEntry(); // iterates over entries in the zip file while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { // if the entry is a file, extracts it extractFile(zipIn, filePath); } else { // if the entry is a directory, make the directory File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (zipIn != null) { try { zipIn.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Unzip file retrived from input stream into directory. * * @param inputStream * input stream of zip file * @param destDirectory * directory to save unziped files * @throws IOException */ public static boolean unzip(InputStream inputStream, String destDirectory) { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zipIn = null; try { zipIn = new ZipInputStream(inputStream); ZipEntry entry = zipIn.getNextEntry(); // iterates over entries in the zip file while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { // if the entry is a file, extracts it extractFile(zipIn, filePath); } else { // if the entry is a directory, make the directory File dir = new File(filePath); dir.mkdir(); } zipIn.closeEntry(); entry = zipIn.getNextEntry(); } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { try { zipIn.close(); } catch (IOException e) { e.printStackTrace(); } } }