java 实现压缩文件和解压文件功能

需要引入ant.1.7.jar 包

package com.zip.util;

import org.junit.jupiter.api.Test;

/**
 * 测试文件的压缩和解压
 *	需要引入ant.1.7.jar 包
 */
public class Dome {
	
	/**
	 * 解压文件
	 */
	@Test	
	public void unFile() {
		try {
			String inputDirectory = "D:/文件备份/apache-tomcat-9.0.19-windows-x64.zip";//需要解压的文件路径
			String outputDirectory = "D:/test/"; //解压后文件保存路径
			new UnZipUtil(inputDirectory,outputDirectory);//调用解压文件工具类
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	/**
	 * 压缩文件
	 */
//	@Test	
//	public void zipFile() {
//		try {
//			String zipFile = "D:/test/apache-tomcat-9.0.19.zip"; //压缩文件的保存路径
//			String filepath = "D:/test/apache-tomcat-9.0.19";//压缩文件的目录
//			new	ZipUtil(zipFile,filepath);//调用压缩文件工具类
//		} catch (Exception e) {
//			System.out.println(e.getMessage());
//		}
//	}

	
}

package com.zip.util;

import java.io.File;
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.ZipFile;

/**
 * 解压缩工具类
 */
public class UnZipUtil {
	private String outputDirectory; //解压缩之后存入的地址
	private String inputDirectory;  //需要解压的文件地址,精确到文件后缀名
	private ZipFile zipFile = null;
	@SuppressWarnings("rawtypes")
	private Enumeration enumer = null;
	
	public UnZipUtil(String inputDirectory,String outputDirectory) throws Exception {
		this.inputDirectory = inputDirectory;
		this.outputDirectory = outputDirectory;
		unZipFile();//调用解压函数方法
	}
	
	private void unZipFile() throws Exception {
		 try {
			zipFile = new ZipFile(this.inputDirectory);
			enumer = zipFile.getEntries();
		    ZipEntry zipEntry = null;
		    createDirectory(this.outputDirectory, "");
			 while (enumer.hasMoreElements()) {
	                zipEntry = (ZipEntry) enumer.nextElement();
	                System.out.println("unziping " + zipEntry.getName());
	                if (zipEntry.isDirectory()) { 
	                    String name = zipEntry.getName();
	                    name = name.substring(0, name.length() - 1);
	                    File f = new File(outputDirectory + File.separator + name);
	                    f.mkdir();
	                } else {
	                    String fileName = zipEntry.getName();
	                    fileName = fileName.replace('\\', '/');
	                    if (fileName.indexOf("/") != -1) {
	                        createDirectory(outputDirectory, fileName.substring(0,fileName.lastIndexOf("/")));
	                    }

	                    File f = new File(outputDirectory
	                            + zipEntry.getName());

	                    f.createNewFile();
	                    InputStream in = zipFile.getInputStream(zipEntry);
	                    FileOutputStream out = new FileOutputStream(f);

	                    byte[] by = new byte[1024];
	                    int c;
	                    while ((c = in.read(by)) != -1) {
	                        out.write(by, 0, c);
	                    }
	                    out.close();
	                    in.close();
	                }
	            }
	            System.out.println("done!");
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception("文件不存在!");
		}
	}
	
    private static void createDirectory(String directory, String subDirectory) throws Exception {
        String dir[];
        File fl = new File(directory);
        try {
            if (subDirectory == "" && fl.exists() != true)
                fl.mkdir(); //创建一个空文件
            else if (subDirectory != "") {
                dir = subDirectory.replace('\\', '/').split("/");
                for (int i = 0; i < dir.length; i++) {
                    File subFile = new File(directory + File.separator + dir[i]);
                    if (subFile.exists() == false)
                        subFile.mkdir();
                    directory += File.separator + dir[i];
                }
            }
        } catch (Exception e) {
        	e.printStackTrace();
        	throw new Exception("文件读取异常");
        }
    }
}

package com.zip.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 压缩文件
 * @author T011921
 *
 */
public class ZipUtil {
    
    private static List list = null;
    
    private byte b[] = null;
    
    private List fileList = null;
    
    //压缩文件的保存路径
    private String zipFile;
    
    //压缩文件目录
    private String filepath;
    
    public ZipUtil(String zipFile,String filepath) {
    	list = new ArrayList<>();
    	b = new byte[512];
    	this.zipFile = zipFile;
    	this.filepath = filepath;
    	fileList = allFile(this.filepath);
    	zip();
    }
    
    /**
     * 压缩
     */
    public void zip() {
        try{
        	FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
    		//使用输出流检查
            CheckedOutputStream cs = new CheckedOutputStream(fileOutputStream, new CRC32());
    		//声明输出zip流
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(cs));
            for (int i = 0; i < fileList.size(); i++) {
               InputStream in = new FileInputStream((String)fileList.get(i));
               String fileName = ((String)(fileList.get(i))).replace(File.separatorChar,'/');
               System.out.println("ziping " + fileName);
               fileName = fileName.substring(fileName.indexOf("/")+1);
               ZipEntry e = new ZipEntry(fileName);
               out.putNextEntry(e);
               int len = 0;
               while((len = in.read(b)) != -1) {
                   out.write(b,0,len);
                 }
               out.closeEntry();
            }
            out.close();  
            System.out.println("done!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @SuppressWarnings("unchecked")
	private static List allFile(String path){       
        File file = new File(path);
        String[] array = null;
        String sTemp = "";
                

        if(file.isDirectory())
        {
        }else{
            return null;
        }
        array= file.list();
        if(array.length>0){
            for(int i=0;i<array.length;i++){
                sTemp = path+array[i];
                file = new File(sTemp);
                if(file.isDirectory()){
                    allFile(sTemp+"/");
                }else{
                    list.add(sTemp);
                }
            }
        }else{
            return null;
        }
        return list;
    }    

}

===============================

package com.zip.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;


public class Zip {
    private static final int BUFFER = 1024;	// Length of buffer
    private long length = 0;				// A uncompress directory's length
    
    /**
 	 * Compress files to *.zip.
 	 * @param fileName: file to be compress
 	 */
    public void compress(String fileName) {
    	String targetFile = null;
    	File sourceFile = new File(fileName);
    	Vector<File> vector = getAllFiles(sourceFile);
        try {
        	if (sourceFile.isDirectory()) {
        		targetFile = fileName + ".zip";
        	} else {
        		char ch = '.';
 				targetFile = fileName.substring(0, fileName.lastIndexOf((int)ch)) + ".zip";
        	}
        	BufferedInputStream bis = null;
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));
            ZipOutputStream zipos = new ZipOutputStream(bos);
            byte data[] = new byte[BUFFER];
            for (int i=0; i<vector.size(); i++) {
            	File file = (File)vector.get(i);
            	zipos.putNextEntry(new ZipEntry(getEntryName(fileName, file)));
            	bis = new BufferedInputStream(new FileInputStream(file));
            	
            	int count;
            	while ((count=bis.read(data, 0, BUFFER)) != -1 ) {
            		zipos.write(data, 0, count);
            	}
            	bis.close();
            	zipos.closeEntry();
            }
            zipos.close();
            bos.close();
            showDetail(sourceFile, new File(targetFile)); 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * Uncompress *.zip files.
     * @param fileName: file to be uncompress
     */
    public void uncompress(String fileName) {
    	File sourceFile = new File(fileName);
    	String filePath = sourceFile.getParent() + "/";
    	try {
    		BufferedInputStream bis = null;
    		BufferedOutputStream bos = null;
    		ZipFile zipFile = new ZipFile(fileName);
    		Enumeration en = zipFile.entries();
    		byte data[] = new byte[BUFFER];
    		while (en.hasMoreElements()) {
    			ZipEntry entry = (ZipEntry)en.nextElement();
    			if (entry.isDirectory()) {
    				new File(filePath + entry.getName()).mkdirs();
    				continue;
    			}
    			bis = new BufferedInputStream(zipFile.getInputStream(entry));
    			File file = new File(filePath + entry.getName());
    			File parent = file.getParentFile();
    			if (parent!=null && (!parent.exists())) {
    				parent.mkdirs();
    			}
    			bos = new BufferedOutputStream(new FileOutputStream(file));
    			int count;
    			while ((count=bis.read(data, 0, BUFFER)) != -1) {
    				bos.write(data, 0, count);
    			}
    			bis.close();
    			bos.close();
    		}
    		zipFile.close();
    	} catch(IOException e) {
    		e.printStackTrace();
    	}
    }
    
    /**
     * To get a directory's all files.
     * @param sourceFile: the source directory
     * @return the files' collection
     */
    private Vector<File> getAllFiles(File sourceFile) {
    	Vector<File> fileVector = new Vector<File>();
    	if (sourceFile.isDirectory()) {
    		File[] files = sourceFile.listFiles();
    		for (int i=0; i<files.length; i++) {
    			fileVector.addAll(getAllFiles(files[i]));
    		}
    	} else {
    		fileVector.add(sourceFile);
    	}
    	return fileVector;
    }

    private String getEntryName(String base,File file) {
        File baseFile=new File(base);
        String filename=file.getPath();
        if(baseFile.getParentFile().getParentFile()==null)
            return filename.substring(baseFile.getParent().length());
        return filename.substring(baseFile.getParent().length()+1);
    }
    
    /**
     * Show the compress or uncompress detail.
     * @param sourceFile: the source file
     * @param targetFile: the target file
     */
    private void showDetail(File sourceFile, File targetFile) {
    	long sourceFileLength = getDirectoryLength(sourceFile);
    	long targetFileLength = targetFile.length();
    	System.out.println("The uncompress file's size is " + sourceFileLength + " bytes.");
    	System.out.println("The compress file's size is " + targetFileLength + " bytes.");
    	System.out.println("The compress rate is " + ((double)(sourceFileLength-targetFileLength)/(double)sourceFileLength)*100 + "%");
    }
    
    /**
     * Get length of a directory.
     * @param path: the directory
     * @return the length of directory
     */
    private long getDirectoryLength(File path) {
    	if (path.isDirectory()) {
    		File[] files = path.listFiles();
    		for (int i=0; i<files.length; i++) {
    			getDirectoryLength(files[i]);
    		}
    	} else {
    		length += path.length();
    	}
    	return length;
    }
    
    public static void main(String[] args) {
//    	if (args.length != 2) {
// 			System.out.println("Usage: java ZipCompress zip/unzip E:/java/apps/zip/text");
// 			return ;
// 		}
// 		Zip zip = new Zip();
// 		if (args[0].equals("zip")) {
// 			zip.compress(args[1]);
// 		} else if(args[0].equals("unzip")) {
// 			zip.uncompress(args[1]);
// 		} else {
// 			System.out.println("Error");
// 		}
 		Zip zip = new Zip();
    	zip.compress("E:/delete/20100422/单向接口");
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值