Java compresses and decompress files in zip format

Source: Internet
Author: User

Reprint: Java JDK instance Treasure

The feeling speaks very well on reprint in this preservation!

Java.util.zip package implements the ZIP format related class library, when compressing and decompressing files using the format zip format, it is necessary to import the package.

Using Zipoutputstream to achieve file compression, all the data written to the Zipoutputstream input stream will be compressed by the ZIP format.

Each compressed file or folder in the zip file corresponding to a ZipEntry object, each zipentry has a Name property, indicating it relative to the zip file folder relative path, for the folder, the path to "/" end, for the file, Brutishness ends with the file name .

Zipoutputstream's Putnextentry method adds zipentry to the zip file, and the data written to the Zipoutputstream stream of the file is saved to ZipEntry, Know the Closeentry method that calls Zipoutputstream.

ZipFile represents a zip file, and its entries method gets the ZipEntry collection in the zip file. The input stream of the Austrian zipentry.

Instance:

Package Book.io;

Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.util.Enumeration;
Import Java.util.zip.ZipEntry;
Import Java.util.zip.ZipFile;
Import Java.util.zip.ZipOutputStream;

/**
* Compress and decompress files or folders with zip
*/
public class Compressutil {

/**
* Compress files or folders
* @param basedirname Compressed root folder
* @param the file or folder name to be compressed under the filename root folder,
* Asterisk * indicates all files under the compressed root folder.
* @param targetfilename Destination zip file
*/
public static void ZipFile (String basedirname, String fileName,
String TargetFileName) {
Detects if the root folder exists
if (Basedirname = = null) {
System.out.println ("Compression failed, root folder does not exist:" + basedirname);
Return
}
File BaseDir = new file (basedirname);
if (!basedir.exists () | | | (!basedir.isdirectory ())) {
System.out.println ("Compression failed, root folder does not exist:" + basedirname);
Return
}
String BaseDirPath = Basedir.getabsolutepath ();
Target file
File TargetFile = new file (TargetFileName);
try{
Create a ZIP output stream to compress the data and write to the zip file
Zipoutputstream out =new Zipoutputstream (
New FileOutputStream (targetfile));
if (Filename.equals ("*")) {
Compress all files under the Basedir folder to zip
Compressutil.dirtozip (BaseDirPath, BaseDir, out);
} else {
File File = new file (BaseDir, fileName);
if (File.isfile ()) {
Compressutil.filetozip (BaseDirPath, file, out);
} else {
Compressutil.dirtozip (BaseDirPath, file, out);
}
}
Out.close ();
SYSTEM.OUT.PRINTLN ("Compressed file succeeded, target file name:" + targetfilename);
} catch (IOException e) {
System.out.println ("Compression failed:" + e);
E.printstacktrace ();
}
}

/**
* Unzip the zip file and unzip the contents of the zip file into the Targetdir folder
* @param zipname ZIP file name to unzip
* @param targetbasedirname target folder
*/
public static void Upzipfile (String zipfilename, String targetbasedirname) {
if (!targetbasedirname.endswith (File.separator)) {
Targetbasedirname + = File.separator;
}
try {
Create a ZipFile object from a zip file
ZipFile zipfile = new ZipFile (zipfilename);
ZipEntry entry = null;
String entryName = null;
String targetfilename = null;
byte[] buffer = new byte[4096];
int bytes_read;
Get all the entry in the zip file
Enumeration Entrys = Zipfile.entries ();
Traverse All Entry
while (Entrys.hasmoreelements ()) {
Entry = (zipentry) entrys.nextelement ();
Get entry's name
EntryName = Entry.getname ();
TargetFileName = Targetbasedirname + entryName;
if (Entry.isdirectory ()) {
If entry is a folder, create a folder
New File (TargetFileName). Mkdirs ();
Continue
} else {
If entry is a file, create a parent folder
New File (TargetFileName). Getparentfile (). Mkdirs ();
}

Otherwise, create the file
File TargetFile = new file (TargetFileName);
System.out.println ("Create file:" + Targetfile.getabsolutepath ());
Open File output stream
FileOutputStream OS = new FileOutputStream (targetfile);
Open entry input stream from a ZipFile object
InputStream is = Zipfile.getinputstream (entry);
while ((Bytes_read = is.read (buffer))! =-1) {
Os.write (buffer, 0, bytes_read);
}
Close the stream
Os.close ();
Is.close ();
}
System.out.println ("Unzip the file successfully!") ");
} catch (IOException err) {
SYSTEM.ERR.PRINTLN ("Uncompressed file failed:" + err);
}
}

/**
* Compress the folder to the zip output stream.
*/
private static void Dirtozip (String basedirpath, File dir,
Zipoutputstream out) {
if (Dir.isdirectory ()) {
List all files under Dir folder
file[] files = dir.listfiles ();
Assume an empty folder
if (Files.length = = 0) {
ZipEntry entry = new ZipEntry (Getentryname (BaseDirPath, dir));
Storing folder information
try {
Out.putnextentry (entry);
Out.closeentry ();
} catch (IOException e) {
E.printstacktrace ();
}
Return
}
for (int i=0; i<files.length; i++) {
if (Files[i].isfile ()) {
If it is a file, call the Filetozip method
Compressutil.filetozip (BaseDirPath, Files[i], out);
} else {
Assume a folder, recursive invocation
Compressutil.dirtozip (BaseDirPath, Files[i], out);
}
}
}
}
/**
* Compress files to the zip output stream
*/
private static void Filetozip (String basedirpath, file file,
Zipoutputstream out) {
FileInputStream in = null;
ZipEntry entry = null;
Create a copy buffer
byte[] buffer = new byte[4096];
int bytes_read;
if (File.isfile ()) {
try {
Create a file input stream
in = new FileInputStream (file);
Make a ZipEntry
Entry = new ZipEntry (getentryname (BaseDirPath, file));
Storing item information to a compressed file
Out.putnextentry (entry);
Copy bytes to compressed file
while ((Bytes_read = in.read (buffer))! =-1) {
Out.write (buffer, 0, bytes_read);
}
Out.closeentry ();
In.close ();
System.out.println ("Add to File"
+ File.getabsolutepath () + "is in the zip file! ");
} catch (IOException e) {
E.printstacktrace ();
}
}
}
/**
* Get the entry name of the file to be compressed in the zip file. Relative path name relative to Folder
* @param BaseDirPath
* @param file
* @return
*/
private static string Getentryname (string basedirpath, file file) {
if (!basedirpath.endswith (File.separator)) {
BaseDirPath + = File.separator;
}
String FilePath = File.getabsolutepath ();
For a folder, you must add "/" after the entry name to indicate that it will be stored as a folder item.
if (File.isdirectory ()) {
FilePath + = "/";
}
int index = Filepath.indexof (BaseDirPath);
Return filepath.substring (Index + basedirpath.length ());
}

public static void Main (string[] args) {
Compress the Temp folder under the C drive, the compressed file is C:/temp.zip
String basedirname = "c:/";
String fileName = "temp/";
String zipfilename = "C:/temp.zip";
Compressutil.zipfile (Basedirname, FileName, zipfilename);
Unzip the zip file you just created to the Temp folder on the D drive
System.out.println ();
FileName = "D:/temp";
Compressutil.upzipfile (Zipfilename, fileName);
}
}

Java compresses and decompress files in zip format

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.