Compression and decompression of ZIP compression format via Java API
Copy Code code as follows:
Package com.hongyuan.test;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.util.Enumeration;
Import Java.util.zip.ZipEntry;
Import Java.util.zip.ZipFile;
Import Java.util.zip.ZipOutputStream;
public class Ziptest {
public static void Main (string[] args) throws IOException {
UnZip ("Bootstrap.zip");
Zip ("Bootstrap_01.zip", "Bootstrap/css/bootstrap.css", "bootstrap/css/bootstrap.min.css");
}
public static void UnZip (String fileName) throws ioexception{
Getting compressed file objects
ZipFile ZF = new ZipFile (fileName);
Traversing file entries
enumeration<? Extends zipentry> items = zf.entries ();
while (Items.hasmoreelements ()) {
ZipEntry item = items.nextelement ();
String FilePath = Zf.getname (). substring (0,
Zf.getname (). LastIndexOf ("."))
+ File.separator + item.getname ();
File Filedir = new file (filepath.substring (0),
Filepath.lastindexof ("/"));
if (!filedir.exists ()) {
Filedir.mkdirs ();
}
Reading files from the stream
OutputStream out = new FileOutputStream (FilePath);
InputStream in = Zf.getinputstream (item);
byte[] temp = new byte[1024];
int len = 0;
while (len = in.read (temp)) > 0) {
Out.write (temp, 0, Len);
}
In.close ();
Out.close ();
}
Zf.close ();
}
public static void Zip (String filename,string ... files) throws ioexception{
Constructing a compressed file output stream
Zipoutputstream zos=new Zipoutputstream (New FileOutputStream (FileName));
for (int i=0,size=files.length;i<size;i++) {
Create a compressed entity
ZipEntry entry=new ZipEntry (files[i].substring (Files[i].lastindexof ("/") +1));
Zos.putnextentry (entry);
Output the contents of a file to a compressed stream
InputStream is=new FileInputStream (Files[i]);
int count=0;
Byte[] Buffer=new byte[1024];
while ((Count=is.read (buffer)) >=0) {
Zos.write (buffer, 0, count);
}
Zos.flush ();
Zos.closeentry ();
Is.close ();
}
}
}