压缩文件以及文件夹

压缩文件以及文件夹

@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

你可能感兴趣的:(压缩文件以及文件夹)