1、ZipInputStream类可读取ZIP压缩格式的文件,包括已压缩和未压缩的条目(entry)。ZipInputStream类的构造方法如下:ZipInputStream(InputStream in);
2、ZipInputStream类的常用方法如表所示:
方法 | 返回值 | 说明 |
read(byte[] b,int off,int len) | int | 读取目标b数组内off偏移量的位置,长度是len字节。 |
available() | int | 判断是否已读完目前entry所指定的数据,已读完返回0,否则返回1。 |
closeEntry() | void | 关闭当前ZIP条目并定位流已读取下一个条目。 |
skip(long n) | long | 跳过当前ZIP条目中指定的字节数。 |
getNextEntry() | ZipEntry | 读取下一个ZipEntry,并将流内的位置移至该entry所指数据的开头。 |
createZipEntry(String name) | ZipEntry | 以指定的name参数新建一个ZipEntry对象。 |
3、下面的实例是将执行压缩文件后生成的压缩文件hello.zip进行解压,解压后的文件储存在ZipEntry类的getName()方法获取的目录下。
package file;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
public class Decompressing {
public static void main(String[] args) {
File file = new File("E:\\hello.zip");//当前压缩文件
ZipInputStream zin;//创建ZipInputStream对象
try {
ZipFile zipFile = new ZipFile(file);//创建压缩文件对象
zin = new ZipInputStream(new FileInputStream(file));//实例化对象,指明要解压的文件
ZipEntry entry ;
while (((entry=zin.getNextEntry())!=null)&& !entry.isDirectory()){//如果entry不为空,并不在同一个目录下
File tmp = new File(entry.getName());//解压出的文件路径
if (!tmp.exists()){//如果文件不存在
tmp.getParentFile().mkdirs();//创建文件父类文件夹路径
OutputStream os = new FileOutputStream(tmp);//将文件目录中的文件放入输出流
//用输入流读取压缩文件中制定目录中的文件
InputStream in = zipFile.getInputStream(entry);
int count = 0;
while ((count = in.read())!=-1){//如有输入流可以读取到数值
os.write(count);//输出流写入
}
os.close();
in.close();
}
zin.closeEntry();
System.out.println(entry.getName()+"解压成功");
}
zin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4、运行结果:
5、总结:
程序执行完毕后,E盘的hello文件夹中将包含hello1.txt和hello2.txt文件。本实例是通过ZipEntry类的getName()方法得知此文件的名称(含path),借此来解压缩之后的目录和文件名。使用ZipInputStream类来解压文件,必须先使用ZipInputStream类的getNextEntry()方法来取得其内的第一个ZipEntry。