前言在工作中,需要将一些数据放入一个zip压缩包中,可以使用ZipOutputStream。ZipOutputStream可以将内容直接写入压缩包中。一般ZipOutputStream通常是先封装一个FileOutputStream来创建,然后在写入文件之前,需要调用一次putNextEntry,然后使用write写入byte[]类型的数据,写入完成后使用closeEntry结束文件打包。当然也可以直接通过ZipOutputStream将数据写入压缩包,在压缩包中构建数据。使用publicstaticvoidfiletest()throwsIOException{StringtxtPath="D:\\fileTest\\image\\2.txt";StringzipPath="D:\\fileTest\\image\\2.zip";//压缩包路径Stringstr="testtest123abc";//要写入的数据//创建压缩包ZipOutputStreamzipOutputStream=newZipOutputStream(newFileOutputStream(zipPath));//封装一个文件FileWriterfileWriter=null;尝试{fileWriter=newFileWriter(txtPath);fileWriter.write(str);fileWriter.flush();fileWriter.close();}catch(IOExceptione){log.error("fileWriter",e);}//封装上面构建一个FileInputStreamFileInputStreamfis=newFileInputStream(txtPath);//在压缩包中创建一个空文件zipOutputStream.putNextEntry(newZipEntry("Request.json"));//写入压缩文件intlen;字节[]缓冲区=新字节[1024];//字节数组大小可调//读取fis字节流,转入buffer字节数组。读取后,fis为空while((len=fis.read(buffer))>0){zipOutputStream.写(缓冲区,0,长度);}字节[]b=新字节[1024];inta=fis.read(b);//关闭压缩包zipOutputStream.closeEntry();fis.close();zipOutputStream.flush();zipOutputStream.close();}复制代码运行后会创建如下文件:压缩包中会生成一个名为Request.json的文件,如图:内容与2.txt中的内容一致,即“测试test123abc”。上面的方法是:先创建2.txt,然后读取2.txt的内容导入到压缩包中形成文件。使用相同的逻辑,我们可以读取任何其他文件并将它们放入存档中。直接将内容导入压缩包中当然我们也可以直接将数据导入压缩包中。实现如下:publicstaticvoidfiletest()throwsIOException{StringzipPath="D:\\fileTest\\image\\3.zip";//压缩包路径Stringstr1="testtest123abc";//需要写入数据Stringstr2="Test2";StringName1=StringUtils.join("file.json");//压缩包中的文件StringName2=StringUtils.join("file/file1.json");//在压缩包中的文件目录下创建一个文件//创建一个压缩包ZipOutputStreamzipOutputStream=newZipOutputStream(newFileOutputStream(zipPath));//在压缩包中创建一个文件zipOutputStream.putNextEntry(newZipEntry(Name1));byte[]bytes1=str1.getBytes(StandardCharsets.UTF_8);zipOutputStream.write(bytes1,0,bytes1.length);//将数据写入压缩包中的文件中zipOutputStream.closeEntry();zipOutputStream.putNextEntry(newZipEntry(Name2));byte[]bytes2=str2.getBytes(StandardCharsets.UTF_8);zipOutputStream.write(bytes2,0,bytes2.length);zipOutputStream.closeEntry();zipOutputStream.flush();zipOutputStream.close();上面的代码直接将String类型的数据转换成byte数组,导入到压缩包中,形成两个文件:文件夹中包含文件1.json,里面文件内容为“test2”,file.json的内容为“testtest123abc”。最后,如果您觉得本文对您有帮助,请点个赞。或者可以加入我的开发交流群:1025263163互相学习,我们会有专业的技术解答。如果您觉得这篇文章对您有用,请给我们的开源项目一个小星星:https://gitee。com/中邦科技非常感谢!PHP学习手册:https://doc.crmeb.com技术交流论坛:https://q.crmeb.com
