zip文件的读取(ZipInputStream)
创建一个ZipInputStream文件,需要传入一个FileInputStream作为数据源,ZipInputStream属于包装器,不能直接对zip文件进行操作。
ZipEntry表示一个压缩文件或目录,getNextEntry的返回值是zipEntry,当getNextEntry返回值为null时循环结束。
代码示例
//遍历压缩包文件
try (ZipInputStream zin = new ZipInputStream(new FileInputStream("c:\\text\\1-201023201325.zip"), Charset.forName("gbk"))) {
ZipEntry entry=null;
//获取压缩文件的每个子文件夹名称、原始长度、压缩后的长度
while((entry=zin.getNextEntry())!=null) {
System.out.println(entry.getName());//输出压缩包的子文件名
System.out.println(entry.getSize());//压缩文件的原始文件长度
System.out.println(entry.getCompressedSize());//压缩文件压缩后的长度
}
} catch (IOException e) {
e.printStackTrace();
}
一、zip文件解压缩
解压缩一个zip文件,需要两大步骤。
首先准备一个和压缩文件名称相同的普通文件,来装解压缩后的文件。然后解析读取压缩文件。
代码示例:
//第一步:准备一个和压缩文件同名的解压缩后存文件的普通文件
//需要解压缩的文件
File zipFile=new File("c:\\text\\1-201023201325.zip");
//提取压缩文件的文件名
String zipFileName=zipFile.getName();
String targetDirName=zipFileName.substring(0,zipFileName.indexOf("."));
//创建解压缩后的文件
File targetDir=new File(zipFile.getParent()+"\\"+targetDirName);
//判断该文件是否存在
while(!targetDir.exists()) {//加了!,不存在为true
targetDir.mkdir();//不存在就创建文件用来存解压缩的文件
}
//第二步:解析Zip文件
//Charset.forName("gbk")为了处理压缩文件的中文字符内容
try (ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile),Charset.forName("gbk"))) {
//遍历zip文件的每个子文件
ZipEntry entry=null;
while((entry=in.getNextEntry())!=null) {
//获取zip压缩包的子文件名称
String entryName=entry.getName();
//解压缩后的子文件的路径=解压缩文件的路径+“\\”+压缩包子文件的名称
String str=targetDir.getPath()+"\\"+entryName;
//创建输出流
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(str));
//读取压缩文件的子文件的字节内容
byte[] buff=new byte[1024];
int len=-1;
while((len=in.read(buff))!=-1) {
//写入解压缩的文件里
out.write(buff,0,len);
}
}
} catch (IOException e) {
e.printStackTrace();
}
二、原始文件写入Zip文件(创建压缩文件)
关键步骤:
1、创建一个和源文件同名同级的压缩文件(同名:原文件的父类路径+“\”+源文件名+“.zip”)
2、获取并遍历原始文件,每遍历一个文件就将其创建成一个压缩文件或目录存入压缩包里,并将其原文件字节内容写入压缩文件
3、关闭压缩文件即可。
代码示例:
File file=new File("C:\\text\\bb");
//创建一个和原始文件同名的zip文件
try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file.getParent()+"\\"+file.getName()+".zip"))) {
//获取并遍历原始文件的子目录列表
File[] files=file.listFiles();
for(File f : files) {
//创建一个ZipEnrty(压缩文件或目录
out.putNextEntry(new ZipEntry(f.getName()));
//将源文件的字节内容,写入zip压缩文件
out.write(Files.readAllBytes(f.toPath()));
//结束当前zipEntry
out.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
}