zoukankan      html  css  js  c++  java
  • Java 压缩文件

    public class Zip {    
         public Zip() {        
         }
        /**
         * 压缩整个目录
         * @param inputFileName
         * @param fileDir
         * @throws HsException 
         * @throws Exception
         */
        public void zip(String zipDirFileName,String fileDir) throws HsException{  
             try {
                zip(zipDirFileName, new File(fileDir));
            } catch (Exception e) {
                throw new HsException(HsErrorMsg.ERR_DEFAULT,"压缩文件夹出错!",e);
            }  
        }
        /**
         * 压缩整个目录 
         * @param zipFileName
         * @param inputFile
         * @throws Exception
         */
        private void zip(String zipFileName, File inputFile) throws Exception {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
            zip(out, inputFile, "");
            System.out.println("zip done");
            out.close();
        }
    
        private void zip(ZipOutputStream out, File f, String base) throws Exception {
            if (f.isDirectory()) {
                File[] fl = f.listFiles();
                out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
                base = base.length() == 0 ? "" : base + "/";
                for (int i = 0; i < fl.length; i++) {
                    zip(out, fl[i], base + fl[i].getName());
                }
            }else {
                out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
                FileInputStream in = new FileInputStream(f);
                int b;
                System.out.println(base);
                while ( (b = in.read()) != -1) {
                    out.write(b);
                }
                in.close();
            }
        }
        /**
         * @param zipFileName为需要解压的zip文件
         * @param extPlace为解压后文件的存放路径
    
         * @param qName 解压后的名字前面加上前缀
         * return  所有文件
    
         * @throws HsException
         */
        public  String[] UnZip(String zipFileName, String extPlace,String qName) throws HsException {
            String  files = "";
            try{
                ZipFile zipFile = new ZipFile(zipFileName);
                Enumeration e = zipFile.getEntries();
                ZipEntry zipEntry = null;
                while (e.hasMoreElements()) {
                    zipEntry = (ZipEntry) e.nextElement();
                    String entryName = zipEntry.getName();
                    String names[] = entryName.split("/");
                    int length = names.length;
                    String path = extPlace;
                    for (int v = 0; v < length; v++) {
                        if (v < length - 1) {
                            path += names[v] + "/";
                            new File(path).mkdir();
                        }else { // 最后一个
    
                            if (entryName.endsWith("/")) { // 为目录,则创建文件夹
                                new File(extPlace + entryName).mkdir();
                            }else {
                                InputStream in = zipFile.getInputStream(zipEntry);
                                OutputStream os = new FileOutputStream(new File(extPlace + qName+entryName));
                                byte[] buf = new byte[1024];
                                int len;
                                while ( (len = in.read(buf)) > 0) {
                                    os.write(buf, 0, len);
                                }
                                files += qName+entryName+"|";
                                in.close();
                                os.close();
                            }
                        }
                    }
              }
              zipFile.close();
              return StringUtils.split(files,"|");
            }catch(Exception e){
                throw new HsException(HsErrorMsg.FILE_ERROR,"文件解压缩出错,文件:"+zipFileName);
            }
      }
        /**
         * 
         * @param zipFileName为需要解压的zip文件
         * @param extPlace为解压后文件的存放路径
    
         * @throws Exception
         */
        public  void UnZip(String zipFileName, String extPlace) throws HsException {
            try{
                ZipFile zipFile = new ZipFile(zipFileName);
                Enumeration e = zipFile.getEntries();
                ZipEntry zipEntry = null;
                while (e.hasMoreElements()) {
                    zipEntry = (ZipEntry) e.nextElement();
                    String entryName = zipEntry.getName();
                    String names[] = entryName.split("/");
                    int length = names.length;
                    String path = extPlace;
                    for (int v = 0; v < length; v++) {
                        if (v < length - 1) {
                            path += names[v] + "/";
                            new File(path).mkdir();
                        }else { // 最后一个
    
                            if (entryName.endsWith("/")) { // 为目录,则创建文件夹
                                new File(extPlace + entryName).mkdir();
                            }else {
                                InputStream in = zipFile.getInputStream(zipEntry);
                                OutputStream os = new FileOutputStream(new File(extPlace + entryName));
                                byte[] buf = new byte[1024];
                                int len;
                                while ( (len = in.read(buf)) > 0) {
                                    os.write(buf, 0, len);
                                }
                                in.close();
                                os.close();
                            }
    } } } zipFile.close(); }
    catch(Exception e){ throw new HsException(HsErrorMsg.FILE_ERROR,"文件解压缩出错,文件:"+zipFileName); } } public static void main(String args[]){ Zip zip = new Zip(); try { //zip.zip("D:\ECLIPSETEST\bots\tamcx\app/bots/infoDown/10001/20080920/1.zip", // "D:\ECLIPSETEST\bots\tamcx\app/bots/infoDown/10001/20080920/zip/"); } catch (Exception e) { // TODO 自动生成 catch 块 e.printStackTrace(); } } }
    public class ZipReadWrite {
    
        public ZipReadWrite() {
    
        }
    
        /**
         * 功能:解压zip文件,解压文件存放在本压缩文件所在目录下
         * 
         * @param zipFileName
         */
        public void ZipUnPack(String zipFileName) throws HsException {
            FileInputStream fin = null;
            ZipInputStream zin = null;
            DataInputStream din = null;
            FileOutputStream fout = null;
            try {
                String filePath = getFileDir(zipFileName);
                if(filePath == null){
                    throw new HsException(HsErrorMsg.ERR_DEFAULT,"文件路径名不合法!");
                }
                fin = new FileInputStream(zipFileName);
                zin = new ZipInputStream(fin);
                din = new DataInputStream(zin);
                ZipEntry ze = null;
                ze = zin.getNextEntry();
                File fi = null;
                while (ze != null) {
                    String enName = ze.getName();
    //                int length = (int) ze.getSize();
    //                byte[] bt = new byte[length];
    //                din.readFully(bt);
                    fi = new File(filePath + enName);
                    fout = new FileOutputStream(fi);
                    IOUtils.copy(new DataInputStream(zin), fout);
    //                fout.write(bt);
                    fout.flush();
                    fout.close();
                    ze = zin.getNextEntry();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new HsException(HsErrorMsg.ERR_DEFAULT, "文件解压缩出现异常!");
            } finally {
                try {
                    if (fin != null) {
                        fin.close();
                    }
                    if (zin != null) {
                        zin.close();
                    }
                    if (din != null) {
                        din.close();
                    }
                } catch (IOException e) {
                    // TODO 自动生成 catch 块
    
                    e.printStackTrace();
                    throw new HsException(HsErrorMsg.ERR_DEFAULT, "文件解压缩关闭出现异常!");
                }
            }
        }
    
        /**
         * 功能:解压zip文件,解压文件存放在指定目录下
    
         * 
         * @param zipFileName
         * @param saveDir
         *            示例:e:/test/test2/ 或e:/test/test2
         * @throws HsException
         */
        public void ZipUnPack(String zipFileName, String saveDir)
                throws HsException {
            FileInputStream fin = null;
            ZipInputStream zin = null;
            DataInputStream din = null;
            FileOutputStream fout = null;
            try {
                String filePath = saveDir;
                String lastChar = saveDir.substring(saveDir.length() - 1, saveDir
                        .length());
                if (!(lastChar.equals("/") || lastChar.equals("\"))) {
                    filePath = saveDir + "/";
                }
                File file = new File(saveDir);
                if (!file.isDirectory()) {
                    file.mkdirs();
                }
                fin = new FileInputStream(zipFileName);
                zin = new ZipInputStream(fin);
                din = new DataInputStream(zin);
                ZipEntry ze = null;
                ze = zin.getNextEntry();
                File fi = null;
                while (ze != null) {
                    String enName = ze.getName();
    //                int length = (int) ze.getSize();
    //                byte[] bt = new byte[length];
    //                din.readFully(bt);
                    fi = new File(filePath + enName);
                    fout = new FileOutputStream(fi);
                    IOUtils.copy(new DataInputStream(zin), fout);
    //                fout.write(bt);
                    fout.flush();
                    fout.close();
                    ze = zin.getNextEntry();
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new HsException(HsErrorMsg.ERR_DEFAULT, "文件解压缩出现异常!");
            } finally {
                try {
                    if (fin != null) {
                        fin.close();
                    }
                    if (zin != null) {
                        zin.close();
                    }
                    if (din != null) {
                        din.close();
                    }
                } catch (IOException e) {
                    // TODO 自动生成 catch 块
    
                    e.printStackTrace();
                    throw new HsException(HsErrorMsg.ERR_DEFAULT, "文件解压缩关闭出现异常!");
                }
            }
        }
    
        /**
         * 功能:得到文件路径的目录名
    
         * 
         * @param filePath     d:dirfilename
         * @return              d:dir
         */
        public String getFileDir(String filePath) {
            String dir = "";
            int i = filePath.lastIndexOf("\");
            int j = filePath.lastIndexOf("/");
            if (i > 0&&j==-1) {
                dir = filePath.substring(0, i + 1);
            } else if(j>0&&i==-1) {
                dir = filePath.substring(0, j + 1);
            }else if(i>j){
                dir = filePath.substring(0, i + 1);
            }else if(j>i){
                dir = filePath.substring(0, j + 1);
            }
            return dir;
        }
    
        public void ZipPack(String fileDir) throws HsException {
            FileOutputStream fout = null;
            DataOutputStream dout = null;
            FileInputStream fin2 = null;
            DataInputStream din2 = null;
            try {
                //去除路径最后的‘/’或者‘’
    
                String lastChar = fileDir.substring(fileDir.length()-1);
                if (lastChar.equals("/") || lastChar.equals("\")) {
                    fileDir = fileDir.substring(0,fileDir.length()-1);
                }
                int last = fileDir.lastIndexOf("/");
                String dirName = null;
                if(last>=0){
                    dirName = fileDir.substring(last+1);
                }else{
                    last = fileDir.lastIndexOf("\");
                    if(last>=0){
                        dirName = fileDir.substring(last+1);
                    }else {
                        throw new HsException(HsErrorMsg.ERR_DEFAULT,"文件目录不合法!");
                    }
                }
                //得到该目录的同名目录
                int lastIndex = fileDir.lastIndexOf("/");
                if(lastIndex<0){
                    lastIndex = fileDir.lastIndexOf("\");
                }
                
                String creatDir = fileDir.substring(0,lastIndex);
                fout = new FileOutputStream(creatDir+"/"+dirName+".zip");
                File file = new File(fileDir);
                File[] files = file.listFiles();
                ZipOutputStream zout = new ZipOutputStream(fout);
                zout.setMethod(ZipOutputStream.DEFLATED);
                dout = new DataOutputStream(zout);
                for (int i = 0; i < files.length; i++) {
                    File fi2 = files[i];
                    fin2 = new FileInputStream(fi2);
                    zout.putNextEntry(new ZipEntry(fi2.getName()));
                    byte[] bt = new byte[fin2.available()];
                    din2 = new DataInputStream(fin2);
                    din2.readFully(bt);
                    dout.write(bt);
                    fin2.close();
                    din2.close();
                }
                dout.flush();
                dout.close();
                zout.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new HsException(HsErrorMsg.ERR_DEFAULT, "压缩zip包时出错!");
            } 
            finally {
                try {
                    if (fout != null) {
                        fout.close();
                    }
                    if (dout != null) {
                        dout.close();
                    }
                } catch (IOException e) {
                    // TODO 自动生成 catch 块
    
                    e.printStackTrace();
                    throw new HsException(HsErrorMsg.ERR_DEFAULT, "文件压缩关闭出现异常!");
                }
            }
        }
    
    
        
    
    }
    public class RaR {   
           /*  
            * cmd 压缩与解压缩命令  
            */  
            private static String rarCmd = "C:\Program Files\WinRAR\Rar.exe a ";    
            private static String unrarCmd = "C:\Program Files\WinRAR\UnRar x ";      
          
           /**  
            * 将1个文件压缩成RAR格式  
            * rarName 压缩后的压缩文件名(不包含后缀)  
            * fileName 需要压缩的文件名(必须包含路径)  
            * destDir 压缩后的压缩文件存放路径  
            */  
            public static void RARFile(String rarName, String fileName, String destDir) {   
               rarCmd += destDir + rarName + ".rar " + fileName;   
               try {   
                   Runtime rt = Runtime.getRuntime();   
                   Process p = rt.exec(rarCmd);   
               }catch(Exception e) {   
                   System.out.println(e.getMessage());         
               }   
            }   
          
           /**  
            * 将1个RAR文件解压  
            * rarFileName 需要解压的RAR文件(必须包含路径信息以及后缀)  
            * destDir 解压后的文件放置目录  
            */  
            public static void unRARFile(String rarFileName, String destDir) {   
               unrarCmd += rarFileName + " " + destDir;   
               try {   
                   Runtime rt = Runtime.getRuntime();   
                   Process p = rt.exec(unrarCmd);    
               } catch (Exception e) {   
                   System.out.println(e.getMessage());      
               }   
            }   
          
        }  
    import java.io.*;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipInputStream;
    
    public class ZipUtils
    {
    
        /**
         *  解压缩zip文件
         * @param sZipPathFile
         * @param sDestPath
         * @return
         * @throws IOException
         */
        public static List<String> extract(String sZipPathFile, String sDestPath) throws IOException
        {
            List<String> allFileName = new ArrayList<String>();
    
            //先指定压缩档的位置和档名,建立FileInputStream对象
            FileInputStream fins = new FileInputStream(sZipPathFile);
            //将fins传入ZipInputStream中
            ZipInputStream zins = new ZipInputStream(fins);
            ZipEntry ze = null;
            byte ch[] = new byte[256];
            while ((ze = zins.getNextEntry()) != null)
            {
                File zfile = new File(sDestPath + ze.getName());
                File fpath = new File(zfile.getParentFile().getPath());
                if (ze.isDirectory())
                {
                    if (!zfile.exists())
                    {
                        zfile.mkdirs();
                    }
                    zins.closeEntry();
                } else
                {
                    if (!fpath.exists())
                    {
                        fpath.mkdirs();
                    }
                    FileOutputStream fouts = new FileOutputStream(zfile);
                    int i;
                    allFileName.add(zfile.getAbsolutePath());
                    while ((i = zins.read(ch)) != -1)
                    {
                        fouts.write(ch, 0, i);
                    }
                    zins.closeEntry();
                    fouts.close();
                }
            }
            fins.close();
            zins.close();
    
            return allFileName;
        }
    
    
        public static void main(String[] args)
        {
            List<String> a = null;
            try
            {
                a = ZipUtils.extract("d:\src.zip", "c:\");
            } catch (IOException e)
            {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            System.out.println(a.size());
    
        }
    
    }
  • 相关阅读:
    Java中的toString、equals方法覆写,懒汉式单例模式,及异常处理
    【Java】String类、Object类、包装类总结
    Java接口练习
    Java面向对象测试
    【Java】二叉搜索树的实现操作及应用
    【Java】实现二叉树基本操作、面试题
    SAS--宏变量
    SAS--array
    SAS--do loop until while
    SAS--设置行号、标记
  • 原文地址:https://www.cnblogs.com/mingforyou/p/4107539.html
Copyright © 2011-2022 走看看