g16g 发表于 2013-2-3 10:38:09

利用java解压.zip的压缩文件

这段代码是我从网上直接复制下来的,写的真的很不错,可以直接运行

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);      }    }
页: [1]
查看完整版本: 利用java解压.zip的压缩文件