ZipInputStream读取zip包中的指定文件小案例-java

首先新建一些zip包,里面包含几个json文件,如下图所示:

这里以读取name1.json为例:

maven依赖

        <!--json的工具类-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.14.0</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.7.1</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.14.0</version&g
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要删除zip包中的某个文件,你可以使用Java中的ZipFile和ZipOutputStream类来实现。以下是一个简单的代码示例: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class DeleteFileFromZipExample { public static void main(String[] args) { String zipFilePath = "example.zip"; String fileToDelete = "fileToDelete.txt"; String tempFilePath = "temp.zip"; try { // 创建一个输入流读取zip文件 ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath)); // 创建一个输出流写入临时zip文件 ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(tempFilePath)); ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { String currentEntry = entry.getName(); // 如果当前entry不是要删除的文件,则将其写入临时zip文件中 if (!currentEntry.equals(fileToDelete)) { zipOutputStream.putNextEntry(new ZipEntry(currentEntry)); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = zipInputStream.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, bytesRead); } } } // 关闭输入和输出流 zipInputStream.close(); zipOutputStream.close(); // 删除原始zip文件 File oldZipFile = new File(zipFilePath); oldZipFile.delete(); // 重命名临时zip文件为原始zip文件的名称 File newZipFile = new File(tempFilePath); newZipFile.renameTo(oldZipFile); System.out.println("文件已删除!"); } catch (IOException e) { System.out.println("文件删除失败!"); e.printStackTrace(); } } } ``` 在这个示例中,我们指定要删除的zip文件的路径和名称以及要删除的文件的名称。然后,我们使用ZipInputStreamZipOutputStream类来读取和写入zip文件。我们遍历zip文件中的所有条目,并将不是要删除的文件条目写入临时zip文件中。一旦完成,我们关闭输入和输出流,删除原始zip文件,将临时zip文件重命名为原始zip文件的名称。如果成功删除文件,将输出"文件已删除!",否则将输出"文件删除失败!"。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值