zipファイルを解凍する

3113 ワード

public class UnzipFile {  
  
    /** 
     *  zip  
     *  
     * @param targetPath   
     * @param zipFilePath   
     */  
    public void unzipFile(String targetPath, String zipFilePath) {  
  
        try {  
            File zipFile = new File(zipFilePath);  
            InputStream is = new FileInputStream(zipFile);  
            ZipInputStream zis = new ZipInputStream(is);  
            ZipEntry entry = null;  
            System.out.println(" :" + zipFile.getName() + "...");  
            // 
           while ((entry = zis.getNextEntry()) != null) {  
                String zipPath = entry.getName(); 
                System.out.println("entry.getName() = "+entry.getName());
               try {  
            	   // 
                    if (entry.isDirectory()) 
                    {  // , 
                        File zipFolder = new File(targetPath + File.separator  
                                + zipPath);  
                        if (!zipFolder.exists()) {  
                            zipFolder.mkdirs();  
                        }  
                    } 
                    else 
                    {  // 
                       File file = new File(targetPath + File.separator  
                               + zipPath);  
                        if (!file.exists()) {  
                            File pathDir = file.getParentFile();  
                           pathDir.mkdirs();  
                           file.createNewFile();  
                       }  

                      FileOutputStream fos = new FileOutputStream(file);  
                        int bread;  
                        while ((bread = zis.read()) != -1) {  
                           fos.write(bread);  
                        }  
                        fos.close();  
  
                    }  
                   System.out.println(" :" + zipPath);  
  
                } catch (Exception e) {  
                    System.out.println(" " + zipPath + " ");  
                  continue;  
                }  
            }  
            zis.close();  
            is.close();  
           System.out.println(" ");  
        } catch (Exception e) {  
           e.printStackTrace();  
        }  
  
    }  
 
    /** 
     * @param args 
     */  
   public static void main(String[] args) {  
	    String path = System.getProperty("user.dir"); // 
	    System.out.println(path);
        String targetPath = path+"\\tmp";   // 
        String zipFile = "D:\\tmp\\ .zip";  // 
        UnzipFile unzip = new UnzipFile();  
        unzip.unzipFile(targetPath, zipFile);  
    }  
  
}