1 10 11 package org.netbeans.modules.piaget.unzip; 12 13 import java.util.zip.*; 14 import java.io.*; 15 16 20 public class Unzipper { 21 22 static String sep = System.getProperty("file.separator"); 23 24 public static String unzipUserFile(String path){ 25 try{ 26 int dotIndex = path.lastIndexOf("."); 28 String dirPathname = path.substring(0, dotIndex); 29 int sepIndex = path.lastIndexOf(sep); 30 String dirName = dirPathname.substring(sepIndex+1); 31 File user = new File(dirPathname); 32 user.mkdir(); 33 34 InputStream in = new BufferedInputStream(new FileInputStream(path)); 36 ZipInputStream zin = new ZipInputStream(in); 37 ZipEntry e; 38 while((e = zin.getNextEntry())!= null) { 39 unzip(zin, dirPathname + sep + e.getName()); 40 } 41 zin.close(); 42 43 unzipDir(dirPathname, dirName); 45 46 return user.getAbsolutePath(); 47 }catch(Exception e){ 48 System.out.println("exception while unzipping"); 49 System.out.println(e.getMessage()); 50 StackTraceElement el[] = e.getStackTrace(); 51 for(int i = 0;i<el.length;i++){ 52 System.out.println(el[i].toString()); 53 } 54 return null; 55 } 56 57 58 } 59 60 private static void unzipDir(String path, String toRemove){ 61 try{ 62 File dir = new File(path); 64 FilenameFilter filter = new FilenameFilter() { 65 public boolean accept(File dir, String name) { 66 return name.endsWith(".zip"); 67 } 68 }; 69 String zip []; 70 zip = dir.list(filter); 71 72 if(zip == null||zip.length == 0){ 73 return; 74 } 75 76 for(int i = 0;i<zip.length;i++){ 77 int dotIndex = zip[i].lastIndexOf("."); 78 String dirName = zip[i].substring(0, dotIndex); 79 dirName = dirName.replaceFirst(toRemove+".", ""); 80 String filePath = path.equals(".") ? "" : path+sep; 81 File f = new File(filePath+dirName); 82 f.mkdir(); 83 InputStream in = new BufferedInputStream(new FileInputStream(filePath+zip[i])); 84 ZipInputStream zin = new ZipInputStream(in); 85 ZipEntry e; 86 while((e = zin.getNextEntry()) != null) { 87 String outName = e.getName().replaceFirst(toRemove+".", ""); 88 unzip(zin, filePath+dirName+sep+outName); 89 } 90 zin.close(); 91 92 unzipDir(filePath+dirName, toRemove); 94 95 File delete = new File(filePath+zip[i]); 96 delete.delete(); 97 } 98 }catch(Exception e){ 99 e.printStackTrace(System.out); 100 } 101 102 } 103 104 105 106 public static void unzip(ZipInputStream zin, String filename) throws IOException { 107 FileOutputStream out = new FileOutputStream(filename); 109 byte [] b = new byte[512]; 110 int len = 0; 111 while ( (len = zin.read(b))!= -1 ) { 112 out.write(b,0,len); 113 } 114 out.close(); 115 } 116 117 } 118 | Popular Tags |