zip文件的读取与写入:

在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();
		}
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雾远望

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值