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=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 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();
        }
    }
}

你可能感兴趣的:(文件)