程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 應用java基本類完成zip緊縮和zip解壓對象類分享

應用java基本類完成zip緊縮和zip解壓對象類分享

編輯:關於JAVA

應用java基本類完成zip緊縮和zip解壓對象類分享。本站提示廣大學習愛好者:(應用java基本類完成zip緊縮和zip解壓對象類分享)文章只能為提供參考,不一定能成為您想要的結果。以下是應用java基本類完成zip緊縮和zip解壓對象類分享正文


應用java基本類寫的一個簡略的zip緊縮解壓對象類


package sun.net.helper;

import java.io.*;
import java.util.logging.Logger;
import java.util.zip.*;

public class ZipUtil {
    private final static Logger logger = Logger.getLogger(ZipUtil.class.getName());
    private static final int BUFFER = 1024*10;

    /**
     * 將指定目次緊縮到和該目次同名的zip文件,自界說緊縮途徑
     * @param sourceFilePath  目的文件途徑
     * @param zipFilePath     指定zip文件途徑
     * @return
     */
    public static boolean zip(String sourceFilePath,String zipFilePath){
        boolean result=false;
        File source=new File(sourceFilePath);
        if(!source.exists()){
            logger.info(sourceFilePath+" doesn't exist.");
            return result;
        }
        if(!source.isDirectory()){
            logger.info(sourceFilePath+" is not a directory.");
            return result;
        }
        File zipFile=new File(zipFilePath+"/"+source.getName()+".zip");
        if(zipFile.exists()){
            logger.info(zipFile.getName()+" is already exist.");
            return result;
        }else{
            if(!zipFile.getParentFile().exists()){
                if(!zipFile.getParentFile().mkdirs()){
                    logger.info("cann't create file "+zipFile.getName());
                    return result;
                }
            }
        }
        logger.info("creating zip file...");
        FileOutputStream dest=null;
        ZipOutputStream out =null;
        try {
            dest = new FileOutputStream(zipFile);
            CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
            out=new ZipOutputStream(new BufferedOutputStream(checksum));
            out.setMethod(ZipOutputStream.DEFLATED);
            compress(source,out,source.getName());
            result=true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                try {
                    out.closeEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(result){
            logger.info("done.");
        }else{
            logger.info("fail.");
        }
        return result;
    }
    private static void compress(File file,ZipOutputStream out,String mainFileName) {
        if(file.isFile()){
            FileInputStream fi= null;
            BufferedInputStream origin=null;
            try {
                fi = new FileInputStream(file);
                origin=new BufferedInputStream(fi, BUFFER);
                int index=file.getAbsolutePath().indexOf(mainFileName);
                String entryName=file.getAbsolutePath().substring(index);
                System.out.println(entryName);
                ZipEntry entry = new ZipEntry(entryName);
                out.putNextEntry(entry);
                byte[] data = new byte[BUFFER];
                int count;
                while((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (origin != null) {
                    try {
                        origin.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else if (file.isDirectory()){
            File[] fs=file.listFiles();
            if(fs!=null&&fs.length>0){
                for(File f:fs){
                    compress(f,out,mainFileName);
                }
            }
        }
    }

    /**
     * 將zip文件解壓到指定的目次,該zip文件必需是應用該類的zip辦法緊縮的文件
     * @param zipFile
     * @param destPath
     * @return
     */
    public static boolean unzip(File zipFile,String destPath){
        boolean result=false;
        if(!zipFile.exists()){
            logger.info(zipFile.getName()+" doesn't exist.");
            return result;
        }
        File target=new File(destPath);
        if(!target.exists()){
            if(!target.mkdirs()){
                logger.info("cann't create file "+target.getName());
                return result;
            }
        }
        String mainFileName=zipFile.getName().replace(".zip","");
        File targetFile=new File(destPath+"/"+mainFileName);
        if(targetFile.exists()){
            logger.info(targetFile.getName()+" already exist.");
            return result;
        }
        ZipInputStream zis =null;
        logger.info("start unzip file ...");
        try {
            FileInputStream fis= new FileInputStream(zipFile);
            CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
            zis = new ZipInputStream(new BufferedInputStream(checksum));
            ZipEntry entry;
            while((entry = zis.getNextEntry()) != null) {
                int count;
                byte data[] = new byte[BUFFER];
                String entryName=entry.getName();
                int index=entryName.indexOf(mainFileName);
                String newEntryName=destPath+"/"+entryName.substring(index);
                System.out.println(newEntryName);
                File temp=new File(newEntryName).getParentFile();
                if(!temp.exists()){
                    if(!temp.mkdirs()){
                        throw new RuntimeException("create file "+temp.getName() +" fail");
                    }
                }
                FileOutputStream fos = new FileOutputStream(newEntryName);
                BufferedOutputStream dest = new BufferedOutputStream(fos,BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
            result=true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(result){
            logger.info("done.");
        }else{
            logger.info("fail.");
        }
        return result;
    }
    public static void main(String[] args) throws IOException {
        //ZipUtil.zip("D:/apache-tomcat-7.0.30", "d:/temp");
        File zipFile=new File("D:/temp/apache-tomcat-7.0.30.zip");
        ZipUtil.unzip(zipFile,"d:/temp") ;
    }
}


另外一個緊縮解壓示例,二個對象年夜家參考應用吧


package com.lanp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * 解壓ZIP緊縮文件到指定的目次
 */
public final class ZipToFile {
 /**
  * 緩存區年夜小默許20480
  */
 private final static int FILE_BUFFER_SIZE = 20480;

 private ZipToFile() {

 }

 /**
  * 將指定目次的ZIP緊縮文件解壓到指定的目次
  * @param zipFilePath  ZIP緊縮文件的途徑
  * @param zipFileName  ZIP緊縮文件名字
  * @param targetFileDir  ZIP緊縮文件要解壓到的目次
  * @return flag    布爾前往值
  */
 public static boolean unzip(String zipFilePath, String zipFileName, String targetFileDir){
  boolean flag = false;
  //1.斷定緊縮文件能否存在,和外面的內容能否為空
  File file = null;   //緊縮文件(領路徑)
  ZipFile zipFile = null;
  file = new File(zipFilePath + "/" + zipFileName);
  System.out.println(">>>>>>解壓文件【" + zipFilePath + "/" + zipFileName + "】到【" + targetFileDir + "】目次下<<<<<<");
  if(false == file.exists()) {
   System.out.println(">>>>>>緊縮文件【" + zipFilePath + "/" + zipFileName + "】不存在<<<<<<");
   return false;
  } else if(0 == file.length()) {
   System.out.println(">>>>>>緊縮文件【" + zipFilePath + "/" + zipFileName + "】年夜小為0不須要解壓<<<<<<");
   return false;
  } else {
   //2.開端解壓ZIP緊縮文件的處置
   byte[] buf = new byte[FILE_BUFFER_SIZE];
   int readSize = -1;
   ZipInputStream zis = null;
   FileOutputStream fos = null;
   try {
    // 檢討能否是zip文件
    zipFile = new ZipFile(file);
    zipFile.close();
    // 斷定目的目次能否存在,不存在則創立
    File newdir = new File(targetFileDir);
    if (false == newdir.exists()) {
     newdir.mkdirs();
     newdir = null;
    }
    zis = new ZipInputStream(new FileInputStream(file));
    ZipEntry zipEntry = zis.getNextEntry();
    // 開端對緊縮包內文件停止處置
    while (null != zipEntry) {
     String zipEntryName = zipEntry.getName().replace('\\', '/');
     //斷定zipEntry能否為目次,假如是,則創立
     if(zipEntry.isDirectory()) {
      int indexNumber = zipEntryName.lastIndexOf('/');
      File entryDirs = new File(targetFileDir + "/" + zipEntryName.substring(0, indexNumber));
      entryDirs.mkdirs();
      entryDirs = null;
     } else {
      try {
       fos = new FileOutputStream(targetFileDir + "/" + zipEntryName);
       while ((readSize = zis.read(buf, 0, FILE_BUFFER_SIZE)) != -1) {
        fos.write(buf, 0, readSize);
       }
      } catch (Exception e) {
       e.printStackTrace();
       throw new RuntimeException(e.getCause());
      } finally {
       try {
        if (null != fos) {
         fos.close();
        }
       } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getCause());
       }
      }
     }
     zipEntry = zis.getNextEntry();
    }
    flag = true;
   } catch (ZipException e) {
    e.printStackTrace();
    throw new RuntimeException(e.getCause());
   } catch (IOException e) {
    e.printStackTrace();
    throw new RuntimeException(e.getCause());
   } finally {
    try {
     if (null != zis) {
      zis.close();
     }
     if (null != fos) {
      fos.close();
     }
    } catch (IOException e) {
     e.printStackTrace();
     throw new RuntimeException(e.getCause());
    }
   }
  }
  return flag;
 }

 /**
  * 測試用的Main辦法
  */
 public static void main(String[] args) {
  String zipFilePath = "C:\\home";
  String zipFileName = "lp20120301.zip";
  String targetFileDir = "C:\\home\\lp20120301";
  boolean flag = ZipToFile.unzip(zipFilePath, zipFileName, targetFileDir);
  if(flag) {
   System.out.println(">>>>>>解壓勝利<<<<<<");
  } else {
   System.out.println(">>>>>>解壓掉敗<<<<<<");
  }
 }

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved