java文件压缩与解压

阅读更多

 一、压缩

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;

public class Compress {
	private final static Logger logger = Logger.getLogger(Compress.class);
	private int k = 1; // 定义递归次数变量  
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
    	Compress book = new Compress();  
        try {  
            book.Compress1("res/date.zip",  
                    new File("res/news"));  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
  
    }
    /**
     * 
     * @param zipName  zip文件名
     * @param inputFile 	输入文件可以是文件夹
     */
    private void Compress1(String zipName , File inputFile) throws Exception{
    	ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipName)) ;
    	BufferedOutputStream bo = new BufferedOutputStream(out);
    	Compress2( out , bo , inputFile , "");
    	out.close();
    	bo.close();
    }
    /**
     * 
     * @param out  zip输出流
     * @param bo   zip输出流装饰类
     * @param file	输入文件或文件夹
     * @param father  上一级文件夹名
     */
    private void Compress2(ZipOutputStream out , BufferedOutputStream bo , File file , String father) throws Exception{
    	if(file.isDirectory()){
    		out.putNextEntry(new ZipEntry(father +file.getName()+"/"));
    		File[] files = file.listFiles();
    		for(File f : files){
   			Compress2(out , bo , f , father+file.getName()+"/");

    		}
    		
    	}
    	else if(file.isFile()){
    		out.putNextEntry(new ZipEntry(father+file.getName()));
    		FileInputStream in = new FileInputStream(file);
    		byte[] buffer = new byte[1024];
    		int length ;
    		while((length = in.read(buffer)) != -1 ){
    			bo.write(buffer);
    		}
    		bo.flush();
    		in.close();
    	}
    }
}

二、解压

package HelloWorld;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

public class reCompress {
	public static void main(String[] args) {
		try {
			unZip(new File("res/news/cc/date.zip"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void unZip(File zipFile) throws IOException {  
        // 得到压缩文件所在目录  
        String path = zipFile.getAbsolutePath();  
        /**替换所有的反斜杠*/
        path = path.replaceAll("\\\\", "/");  
        /**截取压缩文件所在文件夹*/
        path = path.substring(0, path.lastIndexOf("/"));  
        /**获取压缩文件对象*/
        ZipFile zip = new ZipFile(zipFile);  
        InputStream in = null;  
        OutputStream out = null;  
        try {  
        	/**压缩文件中的所有实体循环*/
            for (@SuppressWarnings("rawtypes") Enumeration entries = zip.entries(); entries.hasMoreElements();) {  
            	/**获取一个实体*/
                ZipEntry entry = (ZipEntry) entries.nextElement();  
                /**获取实体名*/
                String zipEntryName = entry.getName();  
                System.out.println(zipEntryName);  
                /**获取实体的输出流*/
                in = zip.getInputStream(entry);  
                // outPath输出目录  
                /**解压后的文件存放在压缩文件同一目录下*/
                String outPath = path + "/" + zipEntryName;  
                // 判断路径是否存在,不存在则创建文件路径
                /**创建文件的文件夹*/
                File file = new File(outPath.substring(0,  outPath.lastIndexOf('/')));  
                if (!file.exists()) {  
                    file.mkdirs();  
                }  
                // 判断文件全路径是否为文件夹,如果是上面已经创建,不需要解压  
                if (new File(outPath).isDirectory()) {  
                    continue;  
                }  
                /**获取文件的输入流,写文件*/
                out = new FileOutputStream(outPath);  
                byte[] buf = new byte[1024];  
                int len;  
                while ((len = in.read(buf)) > 0) {  
                    out.write(buf, 0, len);  
                }  
            }  
        } catch (IOException e) {  
        } finally {  
            if (in != null) { 
                in.close();  
            }  
            if (out != null) {  
                out.close();  
            }  
        }  
        zip.close();  
    }
}

 

你可能感兴趣的:(java,压缩)