栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

用Java进行zip文件压缩与解压缩

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

用Java进行zip文件压缩与解压缩

可能存在的业务情况:

1、用户上传了压缩包,需校验压缩包中的文件是否合格。

2、用户上传压缩包,对压缩包中的文件进行批量水印处理

解决思路:

1、读取原压缩包文件,解压缩至临时目录

2、对临时目录中的解压缩文件进行校验/水印处理

3、对临时目录中处理过的文件进行压缩

4、删除临时目录及其下的文件

需要参考前面的校验PDF的帖子

测试结果如下:

测试代码:

@Test
  public void testZip() {
    String filePath = "D:\pdfTest\合格压缩文件.zip";
    // 获取原文所在目录
    // 服务器上时,文件路径为“/”,此处测试需要换成filePath中的“\”
    //String oldFilePath = filePath.substring(0, filePath.lastIndexOf("/"));
    String oldFilePath = filePath.substring(0, filePath.lastIndexOf("\"));
    System.out.println("原文件路径:" + oldFilePath);
    // 临时目录,原压缩文件解压目录
    String destDirPath = oldFilePath + "\tmp\";
    System.out.println("临时路径:" + destDirPath);
    // 将原压缩文件解压到临时目录
    ZipUtil.unzipFile(filePath, destDirPath);

    // 临时目录文件对象
    File destDir = new File(destDirPath);
    // 获取临时目录下的所有文件
    File[] files = destDir.listFiles();
    // 定义变量,保存校验结果
    List list = new ArrayList<>();
    // 遍历文件,进行校验
    for (File file: files) {
      String absolutePath = file.getAbsolutePath();
      System.out.println(absolutePath);
      int i = CheckPdfHelper.checkPdf(absolutePath);
      list.add(i);
      // 压缩包中存在不合格PDF文件时
      if (i != 0) {
 break;
      }
    }
    // 判断是否包含不合格PDF文件
    if (list.contains(1)) {
      System.out.println("压缩文件中包含不合格PDF文件");
      // 删除解压缩的文件和临时目录
      ZipUtil.deletefile(destDirPath);
      // 不合格时,不生成新的压缩包文件
      return;
    } else {
      System.out.println("压缩文件PDF文件均符合要求");
    }

    // 获取原压缩文件后缀
    int pos = filePath.lastIndexOf('.');
    String suffix = filePath.substring(pos + 1);
    // 新生成压缩文件路径
    String newFilePath = filePath.substring(0, pos) + ".PSW." + suffix;
    System.out.println("新的压缩文件路径:" + newFilePath);

    // 将检验成功的文件压缩成一个新的压缩包
    ZipUtil.zipFile(newFilePath, files);
    // 删除临时目录
    ZipUtil.deletefile(destDirPath);
  }

ZipUtil工具类:

package com.alphajuns.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;


public class ZipUtil {

  
  public static void zipFile( String zip , File[] srcFiles ) {
    try {
      if( zip.endsWith(".zip") || zip.endsWith(".ZIP") ){
 FileOutputStream fos = new FileOutputStream(new File(zip));
 ZipOutputStream _zipOut = new ZipOutputStream(fos) ;
 _zipOut.setEncoding("GBK");
 for( File _f : srcFiles ){
   handlerFile(zip , _zipOut , _f , "");
 }
 fos.close();
 _zipOut.close();
      }else{
 System.out.println("target file[" + zip + "] is not .zip type file");
      }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
  }

  
  private static void handlerFile(String zip , ZipOutputStream zipOut , File srcFile , String path) throws IOException {
    System.out.println(" begin to compression file[" + srcFile.getName() + "]");
    if( !"".equals(path) && ! path.endsWith(File.separator)){
      path += File.separator ;
    }
    if( ! srcFile.getPath().equals(zip) ){
      if( srcFile.isDirectory() ){
 File[] _files = srcFile.listFiles() ;
 if( _files.length == 0 ){
   zipOut.putNextEntry(new ZipEntry( path + srcFile.getName() + File.separator));
   zipOut.closeEntry();
 }else{
   for( File _f : _files ){
     handlerFile( zip ,zipOut , _f , path + srcFile.getName() );
   }
 }
      }else{
 InputStream _in = new FileInputStream(srcFile) ;
 zipOut.putNextEntry(new ZipEntry(path + srcFile.getName()));
 int len = 0 ;
 byte[] _byte = new byte[1024];
 while( (len = _in.read(_byte)) > 0 ){
   zipOut.write(_byte, 0, len);
 }
 _in.close();
 zipOut.closeEntry();
      }
    }
  }

  
  public static List unzipFile(String zipPath, String descDir) {
    return unzipFile(new File(zipPath) , descDir) ;
  }

  
  @SuppressWarnings("rawtypes")
  public static List unzipFile(File zipFile, String descDir) {
    List _list = new ArrayList() ;
    try {
      ZipFile _zipFile = new ZipFile(zipFile , "GBK") ;
      for( Enumeration entries = _zipFile.getEntries() ; entries.hasMoreElements() ; ){
 ZipEntry entry = (ZipEntry)entries.nextElement() ;
 File _file = new File(descDir + File.separator + entry.getName()) ;
 if( entry.isDirectory() ){
   _file.mkdirs() ;
 }else{
   File _parent = _file.getParentFile() ;
   if( !_parent.exists() ){
     _parent.mkdirs() ;
   }
   InputStream _in = _zipFile.getInputStream(entry);
   OutputStream _out = new FileOutputStream(_file) ;
   int len = 0 ;
   byte[] _byte = new byte[1024];
   while( (len = _in.read(_byte)) > 0){
     _out.write(_byte, 0, len);
   }
   _in.close();
   _out.flush();
   _out.close();
   _list.add(_file) ;
 }
      }
    } catch (IOException e) {
    }
    return _list ;
  }

  
  public static void deletefile(String delpath) {
    try {
      File file = new File(delpath);
      if (!file.isDirectory()) {
 file.delete();
      } else if (file.isDirectory()) {
 String[] fileList = file.list();
 for (int i = 0; i < fileList.length; i++) {
   File delfile = new File(delpath + File.separator + fileList[i]);
   if (!delfile.isDirectory()) {
     delfile.delete();
   } else if (delfile.isDirectory()) {
     deletefile(delpath + File.separator + fileList[i]);
   }
 }
 file.delete();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}

以上就是用Java进行zip文件压缩与解压缩的详细内容,更多关于java zip文件压缩与解压缩的资料请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/129620.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号