java如何使用io流将多个文件写入到zip文件中呢?

乔欣 Java经验 发布时间:2023-04-10 20:58:47 阅读数:287 1
下文笔者讲述将多个文件放入到一个zip文件中的方法分享,如下所示

多个文件写入到ZIP文件的实现思路

借助ZipOutputStream对象
   将多个文件依次写入zip中
    即可实现多个文件写入到zip中的效果
例:多个文件写入到zip的实现思路
public static void main(String[] args) throws Exception {
		//分别是三个文件的输入流
		InputStream in1 = new FileInputStream("D:/test/file1.txt");
		InputStream in2 = new FileInputStream("D:/test/file2.txt");
		InputStream in3 = new FileInputStream("D:/test/file3.txt");
		//分别是三个文件读取时的缓冲区大小
		//1024Bytes,也就是说每次读1M,假如文件1有2.5M,那就要读三次
		byte[] b1=new byte[1024];
		byte[] b2=new byte[1024];
		byte[] b3=new byte[1024];
		//每个文件读完后,用一个字符串存储文件内容
		String s1="";
		String s2="";
		String s3="";
		
		//下面这个while循环读文件的代码不知道你看不看得懂,我不知道该怎么写注释,你要是不懂再问我吧
		int len1=0;
		int len2=0;
		int len3=0;
		while((len1=in1.read(b1))!=-1){
			s1+=new String(b1, 0, len1);
		}
		while((len2=in2.read(b2))!=-1){
			s2+=new String(b2, 0, len2);
		}
		while((len3=in3.read(b3))!=-1){
			s3+=new String(b3, 0, len3);
		}
		
		
		
		
		//定义输出流,目的地是aaa.zip
		FileOutputStream fout = new FileOutputStream("D:/test.zip");
		//将三个文件的内容放进一个map里
		Map<String, byte[]> datas = new HashMap<String, byte[]>();
		datas.put("file1.txt", s1.getBytes());
		datas.put("file2.txt", s2.getBytes());
		datas.put("file3.txt", s3.getBytes());

		//装饰器模式:用ZipOutputStream包装输出流,使其拥有写入zip文件的能力
		ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(fout));
		
		//遍历
		Set<String> keys = datas.keySet();
		for (String key : keys) {
			//下面就是循环把每个文件写进zip文件
			InputStream bin = new BufferedInputStream(new ByteArrayInputStream(datas.get(key)));
			byte[] b = new byte[1024];
			
			zipout.putNextEntry(new ZipEntry(key));
			int len = -1;
			while ((len = bin.read(b)) !=-1) {
				zipout.write(b, 0, len);
			}
		}
		zipout.close();	
	}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202304/16811315656204.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者