1 import org.apache.tools.zip.ZipEntry; 2 import org.apache.tools.zip.ZipFile; 3 import java.io.*; 4 import java.util.Enumeration; 5 6 public class ZipUtils { 7 public ZipUtils(){} 8 9 /** 10 * @param sourcefiles 源文件(服务器上的zip包存放地址) 11 * @param decompreDirectory 解压缩后文件存放的目录 12 * @throws IOException IO异常 13 */ 14 @SuppressWarnings("unchecked") 15 public static void unzip(String sourcefiles, String decompreDirectory) throws IOException { 16 ZipFile readfile = null; 17 try { 18 readfile =new ZipFile(sourcefiles); 19 Enumeration takeentrie = readfile.getEntries(); 20 ZipEntry zipEntry = null; 21 File credirectory = new File(decompreDirectory); 22 credirectory.mkdirs(); 23 while (takeentrie.hasMoreElements()) { 24 zipEntry = (ZipEntry) takeentrie.nextElement(); 25 String entryName = zipEntry.getName(); 26 InputStream in = null; 27 FileOutputStream out = null; 28 try { 29 if (zipEntry.isDirectory()) { 30 String name = zipEntry.getName(); 31 name = name.substring(0, name.length() - 1); 32 File createDirectory = new File(decompreDirectory+ File.separator + name); 33 createDirectory.mkdirs(); 34 } else { 35 int index = entryName.lastIndexOf("\\"); 36 if (index != -1) { 37 File createDirectory = new File(decompreDirectory+ File.separator+ entryName.substring(0, index)); 38 createDirectory.mkdirs(); 39 } 40 index = entryName.lastIndexOf("/"); 41 if (index != -1) { 42 File createDirectory = new File(decompreDirectory + File.separator + entryName.substring(0, index)); 43 createDirectory.mkdirs(); 44 } 45 File unpackfile = new File(decompreDirectory + File.separator + zipEntry.getName()); 46 in = readfile.getInputStream(zipEntry); 47 out = new FileOutputStream(unpackfile); 48 int c; 49 byte[] by = new byte[1024]; 50 while ((c = in.read(by)) != -1) { 51 out.write(by, 0, c); 52 } 53 out.flush(); 54 } 55 } catch (IOException ex) { 56 ex.printStackTrace(); 57 throw new IOException("解压失败:" + ex.toString()); 58 } finally { 59 if (in != null) { 60 try { 61 in.close(); 62 } catch (IOException ex) { 63 64 } 65 } 66 if (out != null) { 67 try { 68 out.close(); 69 } catch (IOException ex) { 70 ex.printStackTrace(); 71 } 72 } 73 in=null; 74 out=null; 75 } 76 77 } 78 } catch (IOException ex) { 79 ex.printStackTrace(); 80 throw new IOException("解压失败:" + ex.toString()); 81 } finally { 82 if (readfile != null) { 83 try { 84 readfile.close(); 85 } catch (IOException ex) { 86 ex.printStackTrace(); 87 throw new IOException("解压失败:" + ex.toString()); 88 } 89 } 90 } 91 } 92 93 //测试 94 95 public static void main(String[] args) { 96 try { 97 unzip(new File("E:/Study/java.zip"), "E:/Study/unzip/"); 98 } catch (IOException e) { 99 e.printStackTrace(); 100 } 101 } 102 } 103 104