天天看點

Java進行檔案壓縮

檔案壓縮

運用ZipOutputStream進行檔案壓縮

public static void zipFile(String sourcePath, String fromat) throw Exception{
  File file = new File(sourcePath);
  if (!file.exist()) {
    System.out.print("目标" + sourcePath + "沒有檔案, 無法壓縮");
    return;
  }
  // 壓縮在同級目錄下
  File parent = new File(file.getParent());
  String targetName = parent.getAbsolutePath() + File.separator + file.getName() + "." + suffix;
  FileOutputStream outputStream = new FileOutputStream(targetName);
  ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
  // 去壓縮
  generateFile(zipOutputStream, file, "");
  
  zipOutputStream.close();
}

private static void generateFile(ZipOutputStream out, File file, String dir){
  
  if (file.isDirectory()) {
    File[] flieList = file.listFiles();
    
    // 建立上級目錄的壓縮條目
    out.putNextEntry(new ZipEntry(dir));
    dir = dir.length == 0 : "" ? dir + "/";
    for (File sonFile : fileList){
      generateFile(out, sonFile, dir + sonFile.getName())
    }
     
  } else {
    // 是檔案, 那麼壓縮寫入
    FileInputStream input = new FileInputStream(file);
    // 标記目前檔案的條目
    out.putNextEntry(new ZipEntry(dir));
    
   // 進行寫操作
    int len = 0;
    byte[] temp = byte[1024];
    while((len = input.read(byte)) > 0) {
      out.write(temp, 0, len);
    }
    
    // 關閉輸入流
    input.close();
  }
  
}