最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用java基礎(chǔ)類(lèi)實(shí)現(xiàn)zip壓縮和zip解壓工具類(lèi)分享

 更新時(shí)間:2014年03月11日 09:16:10   作者:  
使用java基礎(chǔ)類(lèi)寫(xiě)的一個(gè)簡(jiǎn)單的zip壓縮解壓工具類(lèi),實(shí)現(xiàn)了指定目錄壓縮到和該目錄同名的zip文件和將zip文件解壓到指定的目錄的功能

使用java基礎(chǔ)類(lèi)寫(xiě)的一個(gè)簡(jiǎn)單的zip壓縮解壓工具類(lèi)

復(fù)制代碼 代碼如下:

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  目標(biāo)文件路徑
     * @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文件必須是使用該類(lèi)的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") ;
    }
}



另一個(gè)壓縮解壓示例,二個(gè)工具大家參考使用吧

復(fù)制代碼 代碼如下:

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 {
 /**
  * 緩存區(qū)大小默認(rèn)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.判斷壓縮文件是否存在,以及里面的內(nèi)容是否為空
  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.開(kāi)始解壓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();
    // 判斷目標(biāo)目錄是否存在,不存在則創(chuàng)建
    File newdir = new File(targetFileDir);
    if (false == newdir.exists()) {
     newdir.mkdirs();
     newdir = null;
    }
    zis = new ZipInputStream(new FileInputStream(file));
    ZipEntry zipEntry = zis.getNextEntry();
    // 開(kāi)始對(duì)壓縮包內(nèi)文件進(jìn)行處理
    while (null != zipEntry) {
     String zipEntryName = zipEntry.getName().replace('\\', '/');
     //判斷zipEntry是否為目錄,如果是,則創(chuàng)建
     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;
 }

 /**
  * 測(cè)試用的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(">>>>>>解壓失敗<<<<<<");
  }
 }

}

相關(guān)文章

  • idea項(xiàng)目debug模式無(wú)法啟動(dòng)的解決

    idea項(xiàng)目debug模式無(wú)法啟動(dòng)的解決

    這篇文章主要介紹了idea項(xiàng)目debug模式無(wú)法啟動(dòng)的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-02-02
  • 整理總結(jié)Java多線程程序編寫(xiě)的要點(diǎn)

    整理總結(jié)Java多線程程序編寫(xiě)的要點(diǎn)

    這篇文章主要介紹了Java多線程程序編寫(xiě)的要點(diǎn),包括線程的狀態(tài)控制和優(yōu)先級(jí)以及線程的通信問(wèn)題等方面,非常之全面!需要的朋友可以參考下
    2016-01-01
  • java實(shí)現(xiàn)桌球小游戲

    java實(shí)現(xiàn)桌球小游戲

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)桌球小游戲,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-07-07
  • SpringBoot+WebSocket實(shí)現(xiàn)IM及時(shí)通訊的代碼示例

    SpringBoot+WebSocket實(shí)現(xiàn)IM及時(shí)通訊的代碼示例

    項(xiàng)目中碰到需要及時(shí)通訊的場(chǎng)景,使用springboot集成websocket,即可實(shí)現(xiàn)簡(jiǎn)單的及時(shí)通訊,本文介紹springboot如何集成websocket、IM及時(shí)通訊需要哪些模塊、開(kāi)發(fā)和部署過(guò)程中遇到的問(wèn)題、以及實(shí)現(xiàn)小型IM及時(shí)通訊的代碼,需要的朋友可以參考下
    2023-10-10
  • JAVA之讀取properties時(shí)路徑的注意問(wèn)題

    JAVA之讀取properties時(shí)路徑的注意問(wèn)題

    這篇文章主要介紹了JAVA之讀取properties時(shí)路徑的注意問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Java中的Comparable和Comparator接口

    Java中的Comparable和Comparator接口

    這篇文章主要介紹了Java中的Comparable和Comparator接口,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容戒殺,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09
  • Java數(shù)組與二維數(shù)組及替換空格實(shí)戰(zhàn)真題講解

    Java數(shù)組與二維數(shù)組及替換空格實(shí)戰(zhàn)真題講解

    數(shù)組對(duì)于每一門(mén)編程語(yǔ)言來(lái)說(shuō)都是重要的數(shù)據(jù)結(jié)構(gòu)之一,當(dāng)然不同語(yǔ)言對(duì)數(shù)組的實(shí)現(xiàn)及處理也不盡相同。Java?語(yǔ)言中提供的數(shù)組是用來(lái)存儲(chǔ)固定大小的同類(lèi)型元素,這篇文章主要介紹了Java數(shù)組與二維數(shù)組及替換空格實(shí)戰(zhàn)真題講解
    2022-07-07
  • Mybatis自定義TypeHandler解決特殊類(lèi)型轉(zhuǎn)換問(wèn)題詳解

    Mybatis自定義TypeHandler解決特殊類(lèi)型轉(zhuǎn)換問(wèn)題詳解

    這篇文章主要介紹了Mybatis自定義TypeHandler解決特殊類(lèi)型轉(zhuǎn)換問(wèn)題詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • java統(tǒng)計(jì)字符串單詞個(gè)數(shù)的方法解析

    java統(tǒng)計(jì)字符串單詞個(gè)數(shù)的方法解析

    在一些項(xiàng)目中可能需要對(duì)一段字符串中的單詞進(jìn)行統(tǒng)計(jì),本文在這里分享了一個(gè)簡(jiǎn)單的demo,有需要的朋友可以拿去看一下
    2017-01-01
  • springboot中rabbitmq實(shí)現(xiàn)消息可靠性機(jī)制詳解

    springboot中rabbitmq實(shí)現(xiàn)消息可靠性機(jī)制詳解

    這篇文章主要介紹了springboot中rabbitmq實(shí)現(xiàn)消息可靠性機(jī)制詳解,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2021-09-09

最新評(píng)論

庆安县| 嘉兴市| 贵州省| 股票| 资源县| 来宾市| 兰溪市| 郧西县| 松桃| 县级市| 巴楚县| 绥江县| 莱西市| 普兰店市| 大厂| 城口县| 东港市| 新和县| 岐山县| 大英县| 伊通| 新巴尔虎左旗| 扶余县| 额济纳旗| 福州市| 宝兴县| 剑阁县| 清新县| 吉隆县| 楚雄市| 阿荣旗| 电白县| 武强县| 原阳县| 阿巴嘎旗| 孝昌县| 哈密市| 焦作市| 台湾省| 什邡市| 南丰县|