栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 压缩和解压缩

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 压缩和解压缩

有些时候,项目中总会用到各种工具类,这些工具类有些是利用第三方jar或者开源的jar,或者Java基础类达到目的。以下是 压缩解压缩的工具类

一、依赖

	org.apache.ant
	ant
	1.10.12

二、Java代码
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;


public class PackUtil {
	private static Logger logger = Logger.getLogger(PackUtil.class);
	 
    public static void generateByType(String path, String type) throws Exception {
        FileOutputStream fout = new FileOutputStream(path + "." + type);
        ZipOutputStream zipOut = new ZipOutputStream(fout);
        try {
            pack(new File(path), zipOut, "");
            zipOut.setEncoding("GBK");  
        } catch (Exception e) {
        	logger.info("异常:打包文件生成" + e.getMessage());
           throw e;
        } finally {
            zipOut.close();
            fout.close();
            clean(new File(path));
        }
    }
    
	
    public static void generateRar(String path) throws Exception {
    	generateByType(path, "rar");
    }
    
    
    public static void generateZip(String path) throws Exception {
    	generateByType(path, "zip");
    }
    
    
    public static void clean(File f) throws Exception{
        String cs[] = f.list();
        if (cs == null || cs.length <= 0) {
            boolean isDelete = f.delete();
            if(!isDelete){
            	throw new Exception(f.getName()+"文件删除失败!");
            }
        } else {
            for (int i = 0; i < cs.length; i++) {
                String cn = cs[i];
                String cp = f.getPath() + File.separator + cn;
                File f2 = new File(cp);
                if (f2.exists() && f2.isFile()) {
                    boolean isDelete = f2.delete();
                    if(!isDelete){
                    	throw new Exception(f2.getName()+"文件删除失败!");
                    }
                } else if (f2.exists() && f2.isDirectory()) {
                    clean(f2);
                }
            }
            boolean isDelete = f.delete();
            if(!isDelete){
            	throw new Exception(f.getName() + "文件删除失败!");
            }
        }
    }
    
    
    private static void pack(File inputFile, ZipOutputStream zipOut, String base) throws Exception {
        FileInputStream fileIn = null;
        try {
            if (inputFile.isDirectory()) {
                File[] files = inputFile.listFiles();
                zipOut.putNextEntry(new ZipEntry(base + File.separator));
                base = base.length() == 0 ? "" : base + File.separator;
                for (int i = 0; i < files.length; i++) {
                	pack(files[i], zipOut, base + files[i].getName());
                }
            } else {
                zipOut.putNextEntry(new ZipEntry(base));
                fileIn = new FileInputStream(inputFile);
                int b;
                while ((b = fileIn.read()) != -1)
                    zipOut.write(b);
                fileIn.close();
            }
        } catch (Exception e) {
        	logger.info("异常:打包失败" + e.getMessage());
            throw e;
        } finally {
        	if(fileIn != null){
        		fileIn.close();
        	}
        }
    }
    
   
    public static void decompre(String zipFilePath, boolean deleteFlag) throws Exception {
         try {
            File file = new File(zipFilePath); 
            // 待解压文件是否存在
            if (file.exists()) {
            	System.out.println("文件存在:" + zipFilePath);
                ZipFile zipFile = new ZipFile(file, "gbk");
                String fileName = file.getName();
                String[] arr = fileName.split("\.");
                // 判断文件夹是否存在
                String parentPath = file.getParent();
                System.out.println("父文件夹:" + parentPath);
                String unZipFilePath =parentPath + File.separator + arr[0];
                System.out.println("加文件名 的父文件夹 :" + unZipFilePath);
               
                File fileParent = new File(unZipFilePath);
                if (!fileParent.isDirectory() && !fileParent.exists()) {
                	System.out.println("创建父文件夹:" + unZipFilePath);
                	fileParent.mkdirs(); // 创建文件夹
                }
                Enumeration e = zipFile.getEntries();
                while (e.hasMoreElements()) {
                	ZipEntry zipEnt = e.nextElement();
                    String zipEntName = zipEnt.getName();
                    // 遍历的文件(绝对路径)
                    File entityFile = new File(parentPath + File.separator  + zipEntName);
                    // 输出的文件
                    File outFile = new File(unZipFilePath + File.separator + zipEntName);
                    System.out.println("遍历文件:" + entityFile.getPath());
                    System.out.println("输出文件:" + outFile.getPath());
                    // 目录
                	if (zipEnt.isDirectory()) { 
                		System.out.println("是目录");
                        if (!outFile.exists()) {
                        	System.out.println("创建目录");
                        	outFile.mkdirs();
                        }
                        continue;
                    } 
                	// 是文件
                	else {
                		System.out.println("是文件");
                    	// 读写文件
                        InputStream is = zipFile.getInputStream(zipEnt);
                        BufferedInputStream bis = new BufferedInputStream(is);
                        
                        if (!outFile.exists()) {
                        	System.out.println("创建文件:" + outFile);
                        	outFile.createNewFile();
                        }
                        FileOutputStream fos = new FileOutputStream(outFile);
                        BufferedOutputStream bos = new BufferedOutputStream(fos);
                        int len;
                        byte[] buff = new byte[1024];
                        while ((len = bis.read(buff)) != -1) {
                            bos.write(buff, 0, len);
                        }
                        bos.close();
                        fos.close();
                    }
                }
                zipFile.close();
            } else {
            	System.out.println("文件不存在");
            }
        } catch (Exception e) {
        	System.out.println("解压文件出现异常:" + e.getMessage());
            throw e;
        }
         // 删除文件
        if (deleteFlag) {
        	FileUtil.deleteFile(zipFilePath);
        }
    }

  
    public static void main(String[] args) throws Exception {
    	String file = "d:\imgs.zip";
    	decompre(file, false);
    	logger.info("解压成功");

	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/877824.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号