Unzip the zip example through the Java API
- 2020-04-01 03:14:42
- OfStack
Through the Java API to achieve zip compression format of compression and decompression
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{
//Gets the compressed file object
ZipFile zf = new ZipFile(fileName);
//Traverses the file entry
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();
}
//Read the file 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{
//Construct 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 file contents to a compression 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();
}
}
}
< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201404/20140411092535.jpg? 201431192634 ">