Zip压缩和解压缩(包括删除压缩的源文件)

来源:互联网 发布:淘宝找回手机真的假的 编辑:程序博客网 时间:2024/05/12 00:34
package com.amarsoft.proj.fds.util;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipOutputStream;import com.amarsoft.are.ARE;public class ZipUtils {/** * 将文件压缩成zip文件 * @param filePath 需要压缩的文件父路径 * @param destZipPath 压缩后的zip文件-(路径+zip包名) */public static void compress(String srcFilePath,String destZipPath) {compress(srcFilePath, destZipPath,false);}/** * 压缩文件 * @param srcPathName 要压缩的文件 * @param zipPathName 压缩后的zip文件 * @param delete 是否删除源文件,true:删除源文件,false:不删除源文件 */public static void compress(String srcPathName,String zipPathName,boolean delete) {      //压缩的文件夹        File srcDir = new File(srcPathName);        //压缩后的zip文件        File destZipFile = new File(zipPathName);        ZipOutputStream out = null;        if (!srcDir.exists())               throw new RuntimeException(srcPathName + "不存在!");           try {               FileOutputStream fileOutputStream = new FileOutputStream(destZipFile);              /* CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,                       new CRC32()); */            BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);            out = new ZipOutputStream(bos);               String basedir = "";               compress(srcDir, out, basedir);              //删除源文件            if (delete) {            deleteFolder(srcPathName);}        } catch (Exception e) {               throw new RuntimeException(e);           }finally{        try {        if (out != null) {        out.close(); }} catch (Exception e) {ARE.getLog().error(e);e.printStackTrace();}        }    }         /**     * 根据文件类型选择压缩一个目录还是文件     * @param file     * @param out     * @param basedir     */    private static void compress(File file, ZipOutputStream out, String basedir) {           /* 判断是目录还是文件 */          if (file.isDirectory()) {               //System.out.println("压缩:" + basedir + file.getName());               compressDirectory(file, out, basedir);           } else {              // System.out.println("压缩:" + basedir + file.getName());               compressFile(file, out, basedir);           }       }         /** 压缩一个目录 */      private static void compressDirectory(File dir, ZipOutputStream out, String basedir) {           if (!dir.exists())               return;             File[] files = dir.listFiles();           for (int i = 0; i < files.length; i++) {               /* 递归 */              compress(files[i], out, basedir + dir.getName() + File.separator);           }       }         /** 压缩一个文件 */      private static void compressFile(File file, ZipOutputStream out, String basedir) {           if (!file.exists()) {               return;           }         //不压缩zip文件        if (file.getName().endsWith(".zip")) {return;}        BufferedInputStream bis = null;        try {               bis = new BufferedInputStream(new FileInputStream(file));               ZipEntry entry = new ZipEntry(basedir + file.getName());               out.putNextEntry(entry);               int count=0;            int buffer = 2048;            byte data[] = new byte[buffer];               while ((count = bis.read(data, 0, buffer)) != -1) {                   out.write(data, 0, count);               }           } catch (Exception e) {               throw new RuntimeException(e);           }finally{         try {         if (bis != null) {         bis.close();}} catch (IOException e) {e.printStackTrace();}        }    }   /**      *  根据路径删除指定的目录或文件,无论存在与否      *@param sPath  要删除的目录或文件      *@return 删除成功返回 true,否则返回 false。      */      public static boolean deleteFolder(String sPath) {          boolean flag = false;          File file = new File(sPath);          // 判断目录或文件是否存在          if (!file.exists()) {  // 不存在返回 false              return flag;          } else {              // 判断是否为文件              if (file.isFile()) {  // 为文件时调用删除文件方法                  return deleteFile(sPath);              } else {  // 为目录时调用删除目录方法                  return deleteDirectory(sPath);              }          }      }          /**      * 删除单个文件      * @param   sPath    被删除文件的文件名      * @return 单个文件删除成功返回true,否则返回false      */      public static boolean deleteFile(String sPath) {          boolean flag = false;          File file = new File(sPath);          // 路径为文件且不为空则进行删除          if (file.isFile() && file.exists()) {              file.delete();              flag = true;          }          return flag;      }          /**      * 删除目录(文件夹)以及目录下的文件      * @param   sPath 被删除目录的文件路径      * @return  目录删除成功返回true,否则返回false      */      public static boolean deleteDirectory(String sPath) {          //如果sPath不以文件分隔符结尾,自动添加文件分隔符          if (!sPath.endsWith(File.separator)) {              sPath = sPath + File.separator;          }          File dirFile = new File(sPath);          //如果dir对应的文件不存在,或者不是一个目录,则退出          if (!dirFile.exists() || !dirFile.isDirectory()) {              return false;          }          boolean flag = true;          //删除文件夹下的所有文件(包括子目录)          File[] files = dirFile.listFiles();          for (int i = 0; i < files.length; i++) {              //删除子文件              if (files[i].isFile()) {                  flag = deleteFile(files[i].getAbsolutePath());                  if (!flag) break;              } //删除子目录              else {                  flag = deleteDirectory(files[i].getAbsolutePath());                  if (!flag) break;              }          }          if (!flag) return false;          //删除当前目录          if (dirFile.delete()) {              return true;          } else {              return false;          }      }  /**       * 解压静态方法       * @param zipFileName  要解压的包-路径+包名     * @param outputDirectory  解压到哪个路径下面     * @throws Exception       */      public static void extract(String zipFileName,String outputDirectory) throws Exception{           try {               org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName);            Enumeration<ZipEntry> e = zipFile.getEntries();              org.apache.tools.zip.ZipEntry zipEntry = null;            //遍历第一个元素            while (e.hasMoreElements()){                zipEntry = (ZipEntry)e.nextElement();                if (zipEntry.isDirectory()){                //元素为目录                    String name=zipEntry.getName();                       name=name.substring(0,name.length()-1);                            mkDirs(outputDirectory+File.separator+name);                                       }else{                 //元素为文件                    String name=zipEntry.getName();                       String dir = name.substring(0,name.lastIndexOf("/"));                       mkDirs(outputDirectory+File.separator+dir);                                        File f=new File(outputDirectory+File.separator+zipEntry.getName());                       f.createNewFile();                       InputStream in = zipFile.getInputStream(zipEntry);                       FileOutputStream out=new FileOutputStream(f);                                          int c;                       byte[] by=new byte[1024];                       while((c=in.read(by)) != -1){                           out.write(by,0,c);                       }                       out.close();                       in.close();                   }               }           }           catch (Exception ex){               System.out.println("解压文件异常"+ex.getMessage());               ex.printStackTrace();           }       }           /**       * 创建目录,包括子目录       * @param dir       * @throws Exception       */      private static void mkDirs(String dir) throws Exception{           if(dir == null || dir.equals("")) return;           File f1 = new File(dir);           if(!f1.exists())               f1.mkdirs();       }   /** * 将文件转换成字节流 * @param zipFilePath 文件路径 * @return 字节流 */public static byte[] zipFileToBytes(File zipFile) {if (zipFile == null) {return null;}//文件不存在if (!zipFile.exists()) {return null;}//输入流FileInputStream zipFin =null;BufferedInputStream zipBin = null;//输出流ByteArrayOutputStream zipBAout = null;BufferedOutputStream zipBos = null;try {//建立文件输入流zipFin = new FileInputStream(zipFile);//过滤流zipBin = new BufferedInputStream(zipFin); // 创建一个新的 byte 数组输出流,它具有指定大小的缓冲区容量  zipBAout = new ByteArrayOutputStream();  //创建一个新的缓冲输出流,以将数据写入指定的底层输出流  zipBos = new BufferedOutputStream(zipBAout);  int buffer = 2048;byte[] data = new byte[2048];int len = 0;//循环从文件中读取数据while ((len = zipBin.read(data, 0, buffer)) != -1) {zipBos.write(data, 0, len);}//刷新此缓冲的输出流zipBos.flush();} catch (FileNotFoundException e) {ARE.getLog().error(e);e.printStackTrace();} catch (IOException e) {ARE.getLog().error(e);e.printStackTrace();}finally{//关闭输入输出流try {if (zipBin != null) {zipBin.close();}} catch (IOException e) {ARE.getLog().error(e);e.printStackTrace();}try {if (zipBos != null) {zipBos.close();}} catch (IOException e) {ARE.getLog().error(e);e.printStackTrace();}}return zipBAout.toByteArray();}/** * 字节流转换成文件 * @param zipPath 将字节转换zip文件(路径+zip名) * @param bytes 要转换的字节数组 */public static void bytesToZipFile(String zipPath,byte[] bytes) {if (bytes == null) {return;}File zipFile = new File(zipPath);//输入流ByteArrayInputStream zipFin =null;BufferedInputStream zipBin = null;//输出流FileOutputStream zipBAout = null;BufferedOutputStream zipBos = null;try {//建立文件输入流zipFin = new ByteArrayInputStream(bytes);//过滤流zipBin = new BufferedInputStream(zipFin); // 创建一个新的 byte 数组输出流,它具有指定大小的缓冲区容量  zipBAout = new FileOutputStream(zipFile);  //创建一个新的缓冲输出流,以将数据写入指定的底层输出流  zipBos = new BufferedOutputStream(zipBAout);  int buffer = 2048;byte[] data = new byte[2048];int len = 0;//循环从文件中读取数据while ((len = zipBin.read(data, 0, buffer)) != -1) {zipBos.write(data, 0, len);}//刷新此缓冲的输出流zipBos.flush();} catch (FileNotFoundException e) {ARE.getLog().error(e);e.printStackTrace();} catch (IOException e) {ARE.getLog().error(e);e.printStackTrace();}finally{//关闭输入输出流try {if (zipBin != null) {zipBin.close();}} catch (IOException e) {ARE.getLog().error(e);e.printStackTrace();}try {if (zipBos != null) {zipBos.close();}} catch (IOException e) {ARE.getLog().error(e);e.printStackTrace();}}}/** * 程序主入口 * @param args * @throws NoSuchAlgorithmException  */public static void main(String[] args) throws Exception {System.out.println("--------------------start--------------------");//压缩20141231001文件夹,压缩后的文件名为testZip.zip/*compress("/home/amarsoft/hkbank/20141231001","/home/amarsoft/hkbank/20141231001.zip");//将zip文件转换为字节流byte[] datas = zipFileToBytes(new File("/home/amarsoft/hkbank/20141231001.zip"));//对字节流进行加密String key = "amarsoft";String encodyString = DESUtils.encrypt(datas, key);System.out.println(encodyString);//对字节流进行解密byte[]  decodeString = DESUtils.decrypt(encodyString, key);//将字节流转换成文件bytesToZipFile("/home/amarsoft/hkbank/Bytes2Zip.zip",decodeString);*///删除指定目录下的文件deleteFolder("/home/amarsoft/20141231001");System.out.println("---------------------end---------------------");}}


0 0
原创粉丝点击