java压缩文件与解压文件的工具类

package com.bonc.uni.utils;

import com.bonc.uni.constant.ResourcePathConstant;
import com.bonc.usdp.odk.logmanager.LogManager;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * ZIP解压缩文件的工具类,文件可以是多级目录的结构进行解压,压缩操作.
 * @author yangwenxue(Vashon)
 *
 */
public class NewZipUtil {
   /**
    * 压缩文件操作
    * @param filePath 要压缩的文件路径
    * @param descDir 压缩文件的保存路径
    * @throws IOException 
    */
   public static void zipFiles(String filePath,String descDir) throws IOException{
      ZipOutputStream zos=null;
      try {
         //创建一个zip输出流
         zos=new ZipOutputStream(new FileOutputStream(descDir));
         //启动压缩
         startZip(zos,"",filePath);
      } catch (FileNotFoundException e) {
         //压缩失败,则删除创建的文件
         File zipFile=new File(descDir);
         if(zipFile.exists()){
            zipFile.delete();
         }
         e.printStackTrace();
      }finally{
         if(zos!=null){
            try {
               zos.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }
   /**
    * 对目录中所有文件递归遍历进行压缩
    * @param zos 压缩输出流
    * @param oppositePath 在zip文件中的相对路径
    * @param filePath 要压缩的文件路径
    * @throws IOException 
    */
   private static void startZip(ZipOutputStream zos, String oppositePath,
         String filePath) throws IOException {
      File file=new File(filePath);
      if(file.isDirectory()){//如果是压缩目录
         File[] files=file.listFiles();//列出所有目录
         for(int i=0;i<files.length;i++){
            File aFile=files[i];
            if(aFile.isDirectory()){//如果是目录,修改相对地址
               String newoppositePath=oppositePath+aFile.getName()+"/";
               //压缩目录,这是关键,创建一个目录的条目时,需要在目录名后面加多一个"/"
               ZipEntry entry=new ZipEntry(newoppositePath);
               zos.putNextEntry(entry);
               zos.closeEntry();
               startZip(zos, newoppositePath, aFile.getPath());
            }else{//如果不是目录,则进行压缩
               zipFile(zos,oppositePath,aFile);
            }
         }
      }else{//如果是压缩文件,直接调用压缩方法进行压缩
         zipFile(zos, oppositePath, file);
      }
   }
   /**
    * 压缩单个文件到目录中
    * @param zos zip输出流
    * @param oppositePath 在zip文件中的相对路径
    * @param file 要压缩的文件
    */
   private static void zipFile(ZipOutputStream zos, String oppositePath, File file) {
      //创建一个zip条目,每个zip条目都必须是相对于跟路径
      InputStream is=null;
      
      try {
         ZipEntry entry=new ZipEntry(oppositePath+file.getName());
         //将条目保存到zip压缩文件当中
         zos.putNextEntry(entry);
         //从文件输入流当中读取数据,并将数据写到输出流当中
         is=new FileInputStream(file);
         //====这种压缩速度很快
         int length=0;
         int bufferSize=1024;
         byte[] buffer=new byte[bufferSize];
         
         while((length=is.read(buffer, 0, bufferSize))>=0){
            zos.write(buffer, 0, length);
         }
         
//===============以下压缩速度很慢=================       
//       int temp=0;
//
//       while((temp=is.read())!=-1){
//          zos.write(temp);
//       }
//==========================================   
         zos.closeEntry();
      } catch (IOException e) {
         e.printStackTrace();
      }finally{
         if(is!=null){
            try {
               is.close();
            } catch (IOException e) {
               LogManager.Exception(e);
            }
         }
      }
   }
   /**
    * 解压文件操作
    * @param zipFilePath zip文件路径
    * @param descDir 解压出来的文件保存的目录
    */
   public static String unZiFiles(String zipFilePath,String descDir){
      List<String> list = new ArrayList<>();
      File zipFile=new File(zipFilePath);
      File pathFile=new File(descDir);
      String outPath=null;
      Charset gbk = Charset.forName("GBK");
      if(!pathFile.exists()){
         pathFile.mkdirs();
      }
      ZipFile zip=null;
      InputStream in=null;
      OutputStream out=null;

      try {
         zip=new ZipFile(zipFile, gbk);
         Enumeration<?> entries=zip.entries();
         while(entries.hasMoreElements()){
            ZipEntry entry=(ZipEntry) entries.nextElement();
            String zipEntryName=entry.getName();
            in = zip.getInputStream(entry);

            outPath=(descDir+"/"+zipEntryName).replace("\\*", "/");
            list.add(outPath);
            //判断路径是否存在,不存在则创建文件路径
            File file=new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if(!file.exists()){
               file.mkdirs();
            }
            //判断文件全路径是否为文件夹,如果是上面已经创建,不需要解压
            if(new File(outPath).isDirectory()){
               continue;
            }
            out = new FileOutputStream(outPath);

            byte[] buf=new byte[4*1024];
            int len;
            while((len=in.read(buf))>=0){
               out.write(buf, 0, len);
            }

            if(in!=null){
               in.close();
            }
            if(out!=null){
               out.close();
            }

         }
      } catch (Exception e) {
         e.printStackTrace();
      }finally{
         try {
            if(zip!=null){
               zip.close();
            }
            if(in!=null){
               in.close();
            }
            if(out!=null){
               out.close();
            }
         } catch (Exception e) {
            LogManager.Exception(e);
         }
         return outPath;
      }
   }

   /**
    * 将multipart类型文件解压
    * @param file
    * @return
    */
   public static String unZiFiles(MultipartFile file){
      String outPath =null;
      try{
         String filePath = ResourcePathConstant.ZIP_PATH + file.getOriginalFilename();
         File desFile = new File(filePath);
         if(!desFile.getParentFile().exists()){
            desFile.mkdirs();
         }
         file.transferTo(desFile);

         outPath = NewZipUtil.unZiFiles(filePath, ResourcePathConstant.ZIP_PATH);
      }catch (Exception e){
         e.printStackTrace();
      }
      return outPath;
   }
   
 /**
     * 解压带文件夹的压缩文件
     * @param fileName
     * @param descDir
     * @throws ZipException
     * @throws IOException
     */

    public static String unZipFile(String fileName, String descDir) throws ZipException,
            IOException {
        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        Charset gbk = Charset.forName("GBK");
        ZipFile zip = new ZipFile(new File(fileName), gbk);
        String outPath =null;
        for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
            // 判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            // 输出文件路径信息
//            System.out.println(outPath);

            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        zip.close();
        return outPath;
    }
}

 /**
 * 从前端接收的zip文件处理  由于只是个测试古将所有的业务逻辑全部放在controller了  望见谅
 * @param fileName * @param descDir
 * @throws ZipException 
 * @throws IOException 
*/
package com.bonc.controller;

import com.bonc.utils.ZipUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RestController
@RequestMapping("/data")
public class DataController {
    @RequestMapping(value = "/zipData" , method = {RequestMethod.POST})
    public String zipData(MultipartFile[] files){
        String zipFilePath="";
        File copyFile = null;
        File unzipFile =null;
        for (MultipartFile file : files) {
            if(file.getOriginalFilename().contains(".zip")){
                String copyPath="F://"+file.getOriginalFilename();
                try {
                    copyFile = new File(copyPath);
                    file.transferTo(copyFile);
                    zipFilePath = ZipUtils.unZipFile(copyPath, "F:/");
                    unzipFile = new File(zipFilePath);
                    if(unzipFile.isDirectory()){
                        File[] files1 = unzipFile.listFiles();
                        for (File file2 : files1) {
                            insertData(file2);
                        }
                    }
                    copyFile.delete();
                    unzipFile.delete();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return zipFilePath;
    }

    public void insertData(File file){
        try {
//            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
//            byte[] bs=new byte[1024];
//            bis.read(bs)
            InputStream inputStream = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            char[] chars = new char[10240];
            int len = reader.read(chars);
            Pattern pattern = Pattern.compile("\\s*|\r|\n|\r\n");
            while (len!=-1){
                String dest="";
                String s = new String(chars, 0, len);
                Matcher matcher = pattern.matcher(s);
                dest=matcher.replaceAll("");
//                s.replace("\r\n","");
//                s.replace("\r","");
//                s.replace("\\s+","");
//                s.replace("\n","");
                len = reader.read(new char[10240]);
            }
            reader.close();
            inputStream.close();
            file.delete();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值