ZipEntry、ZipInputStream和ZipOutputStream三个Java类实现zip数据压缩方式的编程方法。
zip压缩文件结构:一个zip文件由多个entry组成,每个entry有一个唯一的名称,entry的数据项存储压缩数据。
与zip文件有关的几个Java类
・类ZipEntry
public ZipEntry(String name);
name为指定的数据项名。
・类ZipOutputStream
ZipOutputStream实现了zip压缩文件的写输出流,支持压缩和非压缩entry。下面是它的几个函数:
public ZipOutputStream(OutputStream out);
∥利用输出流out构造一个ZIP输出流。
public void setMethod(int method);
∥设置entry压缩方法,缺省值为DEFLATED。
public void putNextEntry(ZipEntry newe);
∥如果当前的entry存在且处于激活状态时,关闭它,在zip文件中写入新的entry-newe
并将数据流定位于entry数据项的起始位置,压缩方法为setMethod指定的方法。
・类ZipInputStream
ZipInputStream实现了zip压缩文件的读输入流,支持压缩和非压缩entry。下面是它的
几个函数:
public ZipInputStream(InputStream in);
∥利用输入流in构造一个ZIP输出流。
public ZipEntry getNextEntry();
∥返回ZIP文件中的下一个entry,并将输出流定位在此entry数据项的起始位置。
public void closeEntry();
∥关闭当前的zip entry,并将数据流定位于下一个entry的起始位置。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.junit.Test;
public class ZipDemo {
public static void main(String[] args) throws Exception {
//压缩后的容器,压缩到哪
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream("f:/abc.zip"));
//一个zip文件由多个entry组成,每个entry有唯一的名称
ZipEntry en = new ZipEntry("a.txt");
//ZipEntry en = new ZipEntry("a\\a.txt");可以在里面建文件夹
zip.putNextEntry(en);
//要压缩的数据源
InputStream in= new FileInputStream("f:/a.txt");
byte[] b = new byte[1024];
int len =0;
while((len=in.read(b))!=-1){
zip.write(b,0,len);
}
zip.closeEntry();
en = new ZipEntry("b.txt");
zip.putNextEntry(en);
in = new FileInputStream("f:/b.txt");
b = new byte[1024];
len = 0;
while((len=in.read(b))!=-1){
zip.write(b, 0, len);
}
zip.closeEntry();
zip.close();
}
@Test
public void jy() throws Exception{
//ZipFile zf = new ZipFile("f:/abc.zip");
//解压的数据源
ZipInputStream zip = new ZipInputStream(new FileInputStream("f:/abc.zip"));
//从zip中取出Entry
ZipEntry en = zip.getNextEntry();
// InputStream in = zf.getInputStream(en);
byte[] b = new byte[1024];
int len =0;
while((len=zip.read(b))!=-1){
String str = new String(b,0,len);
System.err.println(str);
}
}
}
以下是解压: