压缩文件以及文件夹

@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
//使用Groovy 稍微改了下
import
 java.io.File;
import java.io.FileInputStream;
import java.util.zip.GZIPOutputStream 
import java.util.zip.ZipEntry 
import java.util.zip.ZipOutputStream 


class Compress {
    
    
public static gzipFile(from,to) throws IOException{
        def inFile 
= new FileInputStream(from);
        def out 
= new GZIPOutputStream(new FileOutputStream(to));
        
byte[] buffer = new byte[4096];
        def buffer_read 
= 0;
        
while((buffer_read = inFile.read(buffer)) != -1){
//            out.write(buffer,0,buffer_read);//use '<<' replace
            out << buffer;//use '<<' replace
        }
        inFile.close();
        out.close();
    }
    
    
public static zipDirectory(dir,zipFile){
        File dire 
= new File(dir);
        
if(!dire.isDirectory()){
            
throw new IllegalArgumentException('Compress: not a directory:' + dir);
        }
        String[] entries 
= dire.list();
        
byte[] buffer = new byte[4096];
        
int bytes_read;
        
        ZipOutputStream out 
= new ZipOutputStream(new FileOutputStream(zipFile));
        
        entries.each{item 
->
            File f 
= new File(dire,item);
            
if(f.isDirectory()){
                
return ;
            }
            FileInputStream in_file 
= new FileInputStream(f);
            ZipEntry entry 
= new ZipEntry(f.getPath());
            out.putNextEntry (entry);
            
while((bytes_read = in_file.read(buffer)) != -1){
                out 
<< buffer;
            }
            in_file.close();
        }
        out.close();
    }
    
    
static main(args) {
        def from 
= args[0];
        File from_file 
= new File(from);
        def directory 
= from_file.isDirectory();
        def to 
= '';
        
if(directory){
            to 
= from + '.zip';
        }
else{
            to 
= from + '.gz';
        }
        
        
if((new File(to)).exists()){
            println(
'Compress: won\'t overwrite existing file:' + to);
            System.exit(0);
        }
        
if(directory)
            Compress.zipDirectory (from, to);
        
else
            Compress.gzipFile from, to;
    }
}


Kyle Wang

posted on 2011-07-22 12:55 王树东 阅读(285) 评论(0)  编辑  收藏 所属分类: Code Templates


只有注册用户登录后才能发表评论。


网站导航:
 
<2011年7月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

公告

常用链接

留言簿

随笔分类(17)

随笔档案(15)

文章分类(4)

文章档案(5)

收藏夹(4)

Algorithm

Design

Environment Setup

Installer

Maven

MINA

OS

Skills for Java

VIM

搜索

最新评论

阅读排行榜

评论排行榜