Java implements file zip compression or decompression

Source: Internet
Author: User
Zip compression or decompression

Package com. test;

Import java. io .*;
Import java. util .*;
Import java.util.zip. ZipOutputStream;
Import java.util.zip. ZipEntry;
Import java.util.zip. ZipFile;
Public class TestZip {
Public TestZip (){
}
/**
* Compressed file
*
* @ Param srcfile
* File [] list of files to be compressed
* @ Param zipfile
* Compressed File
*/
Public static void ZipFiles (java. io. File [] srcfile, java. io. File zipfile ){
Byte [] buf = new byte [1, 1024];
Try {
// Create the ZIP file
ZipOutputStream out = new ZipOutputStream (new FileOutputStream (
Zipfile ));
// Compress the files
For (int I = 0; I <srcfile. length; I ++ ){
FileInputStream in = new FileInputStream (srcfile [I]);
// Add ZIP entry to output stream.
Out. putNextEntry (new ZipEntry (srcfile [I]. getName ()));
// Transfer bytes from the file to the ZIP file
Int len;
While (len = in. read (buf)> 0 ){
Out. write (buf, 0, len );
}
// Complete the entry
Out. closeEntry ();
In. close ();
}
// Complete the ZIP file
Out. close ();
System. out. println ("COMPRESSED .");
} Catch (IOException e ){
E. printStackTrace ();
}
}
/**
* Extract
*
* @ Param zipfile
* File: the File to be decompressed
* @ Param descDir
* Target directory after String Extraction
*/
Public static void UnZipFiles (java. io. File zipfile, String descDir ){
Try {
// Open the ZIP file
ZipFile zf = new ZipFile (zipfile );
For (Enumeration entries = zf. entries (); entries. hasMoreElements ();){
// Get the entry name
ZipEntry entry = (ZipEntry) entries. nextElement ());
String zipEntryName = entry. getName ();
InputStream in = zf. getInputStream (entry );
OutputStream out = new FileOutputStream (descDir + zipEntryName );
Byte [] buf1 = new byte [1024];
Int len;
While (len = in. read (buf1)> 0 ){
Out. write (buf1, 0, len );
}
// Close the file and stream
In. close ();
Out. close ();
System. out. println ("decompressed .");
}
} Catch (IOException e ){
E. printStackTrace ();
}
}
}

 

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.