java 文件的压缩

 

整理了一下如何进行文件的zip压缩,解压,.不足之处:解压的时候如果是中文名称,会有乱码,暂时没有想到好办法.

之前有zip压缩的时候中文乱码最后用的ant.jar来进行压缩然后解决了中文乱码的问题.


ZipUtil.java

package com.zwy;

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 java.util.zip.ZipException;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.converter.utils.FileUtils;



/**
 * 
 * @author cd0281
 * zip工具包
 */
public final class ZipUtil {
	private static final Logger	_log	= LoggerFactory.getLogger( ZipUtil.class );
	
	/**
    * APDPlat中的重要打包机制
    * 将jar文件中的某个文件夹里面的内容复制到某个文件夹
    * @param jar 包含静态资源的jar包
    * @param subDir jar中包含待复制静态资源的文件夹名称
    * @param loc 静态资源复制到的目标文件夹
    * @param force 目标静态资源存在的时候是否强制覆盖
    */
   public static void unZip(String jar, String subDir, String loc, boolean force){
       try {
           File base=new File(loc);
           if(!base.exists()){
               base.mkdirs();
           }

           ZipFile zip=new ZipFile(new File(jar));
           Enumeration<? extends ZipEntry> entrys = zip.getEntries();
           while(entrys.hasMoreElements()){
               ZipEntry entry = entrys.nextElement();
               String name=entry.getName();
               if(!name.startsWith(subDir)){
                   continue;
               }
               //去掉subDir
               name=name.replace(subDir,"").trim();
               if(name.length()<2){
                   _log.debug(name+" 长度 < 2");
                   continue;
               }
               if(entry.isDirectory()){
                   File dir=new File(base,name);
                   if(!dir.exists()){
                       dir.mkdirs();
                       _log.debug("创建目录");
                   }else{
                       _log.debug("目录已经存在");
                   }
                   _log.debug(name+" 是目录");
               }else{
                   File file=new File(base,name);
                   if(file.exists() && force){
                       file.delete();
                   }
                   if(!file.exists()){
                       InputStream in=zip.getInputStream(entry);
                       FileUtils.copyFile(in,file);
                       _log.debug("创建文件");
                   }else{
                       _log.debug("文件已经存在");
                   }
                   _log.debug(name+" 不是目录");
               }
           }
       } catch (ZipException ex) {
           _log.error("文件解压失败",ex);
       } catch (IOException ex) {
           _log.error("文件操作失败",ex);
       }
   }

  /**
    * 创建ZIP文件
    * @param sourcePath 文件或文件夹路径
    * @param zipPath 生成的zip文件存在路径(包括文件名)
    */
   public static void createZip(String sourcePath, String zipPath) {
       FileOutputStream fos = null;
       ZipOutputStream zos = null;
       try {
           fos = new FileOutputStream(zipPath);
           zos = new ZipOutputStream(fos);
           writeZip(new File(sourcePath), "", zos);
       } catch (FileNotFoundException e) {
    	   _log.error("文件找不到",e);
		e.printStackTrace();
	} finally {
           try {
               if (zos != null) {
                   zos.close();
               }
           } catch (IOException e) {
               _log.error("创建ZIP文件失败",e);
           }

       }
   }

   private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
       if(file.exists()){
           if(file.isDirectory()){//处理文件夹
               parentPath+=file.getName()+File.separator;
               File [] files=file.listFiles();
               for(File f:files){
                   writeZip(f, parentPath, zos);
               }
           }else{
               FileInputStream fis=null;
               try {
                   fis=new FileInputStream(file);
                   ZipEntry ze = new ZipEntry(parentPath + file.getName());
                   zos.putNextEntry(ze);
                   byte [] content=new byte[1024];
                   int len;
                   while((len=fis.read(content))!=-1){
                       zos.write(content,0,len);
                       zos.flush();
                   }

               } catch (FileNotFoundException e) {
                   _log.error("创建ZIP文件失败",e);
               } catch (IOException e) {
                   _log.error("创建ZIP文件失败",e);
               }finally{
                   try {
                       if(fis!=null){
                           fis.close();
                       }
                   }catch(IOException e){
                       _log.error("创建ZIP文件失败",e);
                   }
               }
           }
       }
   }    
   
  
 
   
   public static void main(String[] args) {

	  // ZipUtil.createZip("d://data", "D://data1.zip");
	   ZipUtil.unZip("d://data1.zip", "", "d://data2", true);
   }
	
	
}

FileUtils.java

package com.converter.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;



public class FileUtils {
	
	public static String getFilePrefix(String fileName){
		int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(0, splitIndex);
	}
	
	public static String getFileSufix(String fileName){
		int splitIndex = fileName.lastIndexOf(".");
        return fileName.substring(splitIndex + 1);
	}
	
	public static void copyFile(String inputFile,String outputFile) throws FileNotFoundException{
		File sFile = new File(inputFile);
		File tFile = new File(outputFile);
		FileInputStream fis = new FileInputStream(sFile);
		FileOutputStream fos = new FileOutputStream(tFile);
		int temp = 0;  
        try {  
			while ((temp = fis.read()) != -1) {  
			    fos.write(temp);  
			}
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally{
            try {
				fis.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        } 
	}

	public static void copyFile(InputStream fis, File file) {
		
		File tFile = file;
		if(!file.exists()) {
			file.mkdirs();
			file.delete( ) ;
		}
		FileOutputStream fos = null;
        try {  
        	 fos = new FileOutputStream(tFile);
     		int temp = 0;
     		byte[] b = new byte[1024];     		
			while ((temp = fis.read(b)) != -1) {  
			    fos.write(temp);  
			}
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally{
            try {
				fis.close() ;
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        } 
		
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值