前言
工作中须要把一些数据放到一个zip的压缩包中,能够应用 ZipOutputStream。ZipOutputStream能够将内容间接写入到zip包中。个别创立ZipOutputStream通常是先封装一个FileOutputStream,而后在每写入一个文件之前,须要先调用一次putNextEntry,而后应用write写入byte[]类型的数据,当写入结束的时候应用colseEntry来完结这个文件的打包。当然也能够通过ZipOutputStream间接把数据写入压缩包内,在压缩包内构建数据。
应用
public static void filetest() throws IOException {
String txtPath = "D:\\fileTest\\image\\2.txt"; String zipPath = "D:\\fileTest\\image\\2.zip"; //压缩包门路 String str = "测试test123abc"; //须要写入的数据 //创立压缩包 ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath)); //封装一个文件 FileWriter fileWriter = null; try { fileWriter = new FileWriter(txtPath); fileWriter.write(str); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { log.error("fileWriter", e); } //对下面封装好的文件构建一个FileInputStream FileInputStream fis = new FileInputStream(txtPath); //压缩包里创立一个空文件 zipOutputStream.putNextEntry(new ZipEntry("Request.json")); //写入压缩文件 int len; byte[] buffer = new byte[1024]; //字节数组大小可调节 //读取fis字节流,转移到buffer字节数组中去,读取后fis为空 while ((len = fis.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, len); } byte[] b = new byte[1024]; int a = fis.read(b); //敞开压缩包打包 zipOutputStream.closeEntry(); fis.close(); zipOutputStream.flush(); zipOutputStream.close();}
复制代码
运行之后,将会创立如下文件:
压缩包内会产生一个叫Request.json文件,如图:
内容与2.txt里的内容统一,为“测试test123abc”。
上述办法是:先创立2.txt,再读取2.txt的内容,导入到压缩包内造成文件。雷同的逻辑,咱们能够读取任意其余文件,而后把他们放入到压缩包内。
间接将内容导入到压缩包内
当然咱们也能够间接将数据导入到压缩包内。实现如下:
public static void filetest() throws IOException {
String zipPath = "D:\\fileTest\\image\\3.zip"; //压缩包门路 String str1 = "测试test123abc"; //须要写入的数据 String str2 = "测试2"; String Name1 = StringUtils.join("文件.json"); //压缩包里的文件 String Name2 = StringUtils.join("file/文件1.json"); //在压缩包里创立file目录下的文件 //创立压缩包 ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath)); //创立压缩包里的文件 zipOutputStream.putNextEntry(new ZipEntry(Name1)); byte[] bytes1 = str1.getBytes(StandardCharsets.UTF_8); zipOutputStream.write(bytes1, 0, bytes1.length); //将数据写入到压缩包里的文件外面 zipOutputStream.closeEntry(); zipOutputStream.putNextEntry(new ZipEntry(Name2)); byte[] bytes2 = str2.getBytes(StandardCharsets.UTF_8); zipOutputStream.write(bytes2, 0, bytes2.length); zipOutputStream.closeEntry(); zipOutputStream.flush(); zipOutputStream.close();
}
复制代码
上述是间接将String类型数据转换成byte数组,导入到压缩包内,造成两个文件:
file文件夹外面是文件1.json,外面的内容是“测试2”,文件.json的内容则是“测试test123abc”。
最初
如果你感觉此文对你有一丁点帮忙,点个赞。或者能够退出我的开发交换群:1025263163互相学习,咱们会有业余的技术答疑解惑
如果你感觉这篇文章对你有点用的话,麻烦请给咱们的开源我的项目点点star: https://gitee.com/ZhongBangKeJi不胜感激 !
PHP学习手册:https://doc.crmeb.com
技术交换论坛:https://q.crmeb.com