자바 압축 파일 과 압축 풀기 도구 클래스

10075 단어 문건
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|
|\r
"); while (len!=-1){ String dest=""; String s = new String(chars, 0, len); Matcher matcher = pattern.matcher(s); dest=matcher.replaceAll(""); // s.replace("\r
",""); // s.replace("\r",""); // s.replace("\\s+",""); // s.replace("
",""); len = reader.read(new char[10240]); } reader.close(); inputStream.close(); file.delete(); } catch (Exception e) { e.printStackTrace(); } } }

좋은 웹페이지 즐겨찾기