Java compression for files and folders

Source: Internet
Author: User
Method 1:

Use Java to implement zip compressed files and directory program code

Today I wrote a Java compression function to compress files and directories.

Because java.util.zip.zipoutputstreamis a Chinese garbled question, org.apache.tools.zip. zipoutputstream is used.

The following code is used:
Java code
Package net.szh.zip;

Import java. Io. bufferedinputstream;
Import java. Io. file;
Import java. Io. fileinputstream;
Import java. Io. fileoutputstream;
Import java.util.zip. CRC32;
Import java.util.zip. checkedoutputstream;

Import org.apache.tools.zip. zipentry;
Import org.apache.tools.zip. zipoutputstream;

Public class zipcompressor {
Static final int buffer = 8192;

Private file zipfile;

Public zipcompressor (string pathname ){
Zipfile = new file (pathname );
}

Public void compress (string srcpathname ){
File file = new file (srcpathname );
If (! File. exists ())
Throw new runtimeexception (srcpathname + "does not exist! ");
Try {
Fileoutputstream = new fileoutputstream (zipfile );
Checkedoutputstream cos = new checkedoutputstream (fileoutputstream,
New CRC32 ());
Zipoutputstream out = new zipoutputstream (COS );
String basedir = "";
Compress (file, out, basedir );
Out. Close ();
} Catch (exception e ){
Throw new runtimeexception (E );
}

}

Private void compress (File file, zipoutputstream out, string basedir ){
/* Determine whether it is a directory or a file */
If (file. isdirectory ()){
System. Out. println ("compression:" + basedir + file. getname ());
This. compressdirectory (file, out, basedir );
} Else {
System. Out. println ("compression:" + basedir + file. getname ());
This. compressfile (file, out, basedir );
}
}

/** Compress a directory */
Private void compressdirectory (File Dir, zipoutputstream out, string basedir ){
If (! Dir. exists ())
Return;

File [] files = dir. listfiles ();
For (INT I = 0; I <files. length; I ++ ){
/* Recursion */

Compress (files [I], out, basedir + dir. getname () + "/");
}
}

/** Compress a file */
Private void compressfile (File file, zipoutputstream out, string basedir ){
If (! File. exists ()){
Return;
}
Try {
Bufferedinputstream Bis = new bufferedinputstream (
New fileinputstream (File ));
Zipentry entry = new zipentry (basedir + file. getname ());
Out. putnextentry (entry );
Int count;
Byte data [] = new byte [buffer];
While (COUNT = bis. Read (data, 0, buffer ))! =-1 ){
Out. Write (data, 0, count );
}
Bis. Close ();
} Catch (exception e ){

Throw new runtimeexception (E );
}
}
}

 

 

 

      Method 2: import  java.io.*;
import  org.apache.log4j.Logger;
import  org.apache.tools.zip.ZipEntry;
import  org.apache.tools.zip.ZipFile;
import  org.apache.tools.zip.ZipOutputStream;
   public  class  ZipCompress {
     private  static  Logger log = Logger.getLogger(ZipCompress. class );
    public  static  void  zip(File inputFile, String zipFileName) {
   try  {
    // Create a file output object out. The prompt is: note that Chinese characters are supported.
    FileOutputStream out =  new  FileOutputStream(
      new  String(zipFileName.getBytes( "UTF-8" ))); 
    // Extract the file from the zip output stream.
    ZipOutputStream zOut =  new  ZipOutputStream(out);   
    log.info( "Compression --> start" );
         zip(zOut, inputFile,  "" );
         log.info( "Compression --> end" );
    zOut.close();
       }  catch  (Exception e) {  
    e.printStackTrace();
   }
     }  
     public  static  void  zip(ZipOutputStream zOut, File file, String base) {  
   try  { 
       // If the file handle is a directory
    if  (file.isDirectory()) {
     // Obtain files in the directory
     File[] listFiles = file.listFiles();
     // Create a ZIP entry
     zOut.putNextEntry( new  ZipEntry(base +  "/" ));     
     log.info( "Directory name :" +file.getName()+ "| Add a ZIP entry :" +base+ "/" );
            base =( base.length() ==  0  ?  ""  : base +  "/"  );
            // Traverse files in the directory
     for  ( int  i =  0 ; i < listFiles.length; i++) {
      // Recursively enter this method
      zip(zOut, listFiles[i], base + listFiles[i].getName());
     }
    }
    // If the file handle is a file
    else  {
     if  (base ==  "" ) {  
      base = file.getName();
     }
     // Fill in the file handle
     zOut.putNextEntry( new  ZipEntry(base));
     log.info( "File name :" +file.getName()+ "| Add a ZIP entry :" +base);
            // Start compression
     // Read from the file stream and write the ZIP file to the stream
     writeFile(zOut,file);
    }
        }  catch  (Exception e) {
    e.printStackTrace();
   }
     } 
     public  static  void  writeFile(ZipOutputStream zOut,File file)  throws  IOException{
   log.info( "Start compression" +file.getName());
   FileInputStream in =  new  FileInputStream(file);  
   int  len;
   while  ((len = in.read()) != - 1 )
    zOut.write(len);
   log.info( "Compression ended" +file.getName());
   in.close();
  }
    public  static  void  main(String[] args) {
      zip( new  File( "C:/test/DATA/reportFile/" + "TASK" + 10421 ),  "c:/ziptest.zip" );
     }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.