在Java中,zip文件的读取和写入需要引入ZipInputStream 和 ZipOutputStream。
先说zip文件的读取:
ZipInputStream继承自InflaterInputStream,而InflaterInputStream又继承自FilterInputStream,
因此ZipInputStream属于包装器,他不可以直接对zip文件进行操作,在使用时需要传入一个InputStream的子类作为数据源,当创建好ZipInputStream的对象后,需要循环调用getNextEntry()方法,当getNextEntry()的返回值为null时循环结束,getNextEntry()方法的返回值类型为ZipEntry,作用是为了获取压缩文件的每个子文件(压缩文件或目录),要想获取压缩文件的内容,就需要调用read()方法进行不断读取,直到返回-1:
zip文件的读取代码如下:
public class Input {
public static void main(String[] args) {
try (ZipInputStream zis = new ZipInputStream(new FileInputStream("D:\\琐碎\\科技ppt.zip"),Charset.forName("gbk"))) {
ZipEntry entry=null;
//获取压缩文件的每个子文件
while((entry=zis.getNextEntry())!=null) {
System.out.println(entry.getName());//输出压缩包中子文件的文件名
System.out.println(entry.getSize());
System.out.println(entry.getCompressedSize());
System.out.println(entry.getLastModifiedTime());
if(!entry.isDirectory()) {
byte[] buff=new byte[128];
int len = -1;
while((len = zis.read(buff))!= -1){
System.out.println(Arrays.toString(buff));
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
zip文件的写入:
同理,在使用ZipOutputStream也需要传入一个InputStream的子类作为数据源,在写入一个文件前
首先需要调用putNextEntry()方法,目的是为了创建一个ZipEntry
然后调用write()方法将原文件的字节内容,写入zip压缩包,需要注意的是写入的zip压缩包应与原始目录在同一父级目录下。
写入完毕后调用closeEntry()结束这个文件的打包。
zip文件的写入代码如下:
public class Input {
public static void main(String[] args) {
//原始目录
File file=new File("D:\\琐碎\\文件操作");
//将原始目录中的文件,“写入”zip压缩文件
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.getParent()+"\\"+file.getName()+".zip"))) {
//获取并遍历原始目录下的子文件列表
File[] files=file.listFiles();
for(File f:files) {
//创建一个ZipEntry
zos.putNextEntry(new ZipEntry(f.getName()));
//将原文件的字节内容,写入zip压缩包
zos.write(Files.readAllBytes(f.toPath()));
//结束当前ZipEntry
zos.closeEntry();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}