Java实现创建Zip压缩包并写入文件

前言

工作中需要把一些数据放到一个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();
    }
复制代码

运行之后,将会创建如下文件:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hT8kTj3R-1642138459115)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1642137599734.png)]

压缩包内会产生一个叫Request.json文件,如图:

<img src="C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1642137772143.png" alt="1642137772143" style="zoom:80%;" />

内容与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数组,导入到压缩包内,形成两个文件:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EaDV1Us3-1642138459116)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1642138303457.png)]

file文件夹里面是文件1.json,里面的内容是“测试2”,文件.json的内容则是“测试test123abc”。

链接:https://juejin.cn/post/7052933194345103390
 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在不解压缩的情况下替换zip压缩包中的指定文件,可以使用JavaZipFile和ZipOutputStream类。 首先,使用ZipFile读取原始Zip文件,并且使用ZipOutputStream创建一个新的Zip文件。然后,遍历ZipFile中的所有条目,并将所有条目写入新的ZipOutputStream中,除了要替换的文件。当到达要替换的文件时,使用ZipEntry将文件添加到新的ZipOutputStream中,以便替换原始文件。 以下是一个示例代码: ```java import java.io.*; import java.util.*; import java.util.zip.*; public class ReplaceZipFileEntry { public static void main(String[] args) throws Exception { String zipFileName = "example.zip"; String fileToReplace = "file.txt"; String replacementFileName = "replacement.txt"; // Open the original zip file and create a new one File zipFile = new File(zipFileName); File tempZipFile = new File("temp.zip"); ZipFile zip = new ZipFile(zipFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempZipFile)); // Loop through all the entries in the original zip file Enumeration entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); // If this is the file to be replaced, add the replacement file instead if (entry.getName().equals(fileToReplace)) { File replacementFile = new File(replacementFileName); FileInputStream fis = new FileInputStream(replacementFile); zos.putNextEntry(new ZipEntry(entry.getName())); byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } fis.close(); } else { // Otherwise, copy the original entry to the new zip file zos.putNextEntry(entry); InputStream is = zip.getInputStream(entry); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { zos.write(buffer, 0, length); } is.close(); } } // Close the streams and delete the original zip file zos.close(); zip.close(); zipFile.delete(); // Rename the temporary zip file to the original name tempZipFile.renameTo(zipFile); } } ``` 在此示例中,我们将替换example.zip文件中名为file.txt的文件。我们使用replacement.txt文件替换它。在代码中,我们首先打开原始zip文件并创建一个新的zip文件(temp.zip)。然后,我们遍历原始zip文件中的所有条目,并将它们添加到新的zip文件中。如果我们到达要替换的文件,我们使用ZipEntry添加replacement.txt文件。最后,我们关闭所有流,删除原始zip文件,并将临时zip文件重命名为原始zip文件的名称。 请注意,这种方法适用于仅替换一个或两个文件的情况。如果您需要替换多个文件,最好解压缩整个zip文件,替换所需的文件,然后重新压缩整个zip文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值