Java的ZipFile报错:Caused by: java.util.zip.ZipException: invalid CEN header (bad entry name)

本文介绍了解决Windows系统下使用Java的ZipFile时遇到的“invalidCENheader(badentryname)”错误的方法。通过指定gbk编码格式,可以有效避免由编解码引起的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Windows系统上跑Java的ZipFile报错:Caused by: java.util.zip.ZipException: invalid CEN header (bad entry name)

Caused by: java.util.zip.ZipException: invalid CEN header (bad entry name)

原因是编解码出现错误,加入gbk编码格式解决:

ZipFile zf = new ZipFile(file, Charset.forName("GBK"));

出现 "java.util.zip.ZipException: no current ZIP entry" 错误通常是因为在创建 ZIP 文件时没有正确设置 ZIP 文件的当前条目。 在上述示例中,确保在将文件添加到 ZIP 文件中时,使用正确的 `putNextEntry` 方法来设置当前的 ZIP 条目。以下是修改后的示例代码: ```java import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.*; import java.io.*; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class S3FileFilterExample { public static void main(String[] args) throws IOException { S3Client s3Client = S3Client.builder() .region(Region.YOUR_REGION) .credentialsProvider(DefaultCredentialsProvider.create()) .build(); String bucketName = "your-bucket-name"; String folderPath = "your-folder-path"; Instant startTime = Instant.now().minus(1, ChronoUnit.DAYS); // 设置起始时间,这里设置为1天前 Instant endTime = Instant.now(); // 设置结束时间,这里设置为当前时间 ListObjectsV2Request listRequest = ListObjectsV2Request.builder() .bucket(bucketName) .prefix(folderPath) .build(); ListObjectsV2Response listResponse = s3Client.listObjectsV2(listRequest); File zipFile = new File("path/to/save/zip/file.zip"); try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile))) { for (S3Object s3Object : listResponse.contents()) { if (s3Object.lastModified().isAfter(startTime) && s3Object.lastModified().isBefore(endTime)) { GetObjectRequest getRequest = GetObjectRequest.builder() .bucket(bucketName) .key(s3Object.key()) .build(); ResponseBytes<GetObjectResponse> responseBytes = s3Client.getObjectAsBytes(getRequest); // 将文件添加到 ZIP 文件中 zipOutputStream.putNextEntry(new ZipEntry(s3Object.key())); zipOutputStream.write(responseBytes.asByteArray()); zipOutputStream.closeEntry(); } } } } } ``` 确保适当地调用 `zipOutputStream.putNextEntry` 来设置当前的 ZIP 条目,然后将文件内容写入 ZIP 文件中。这样可以避免 "no current ZIP entry" 错误。 如果你仍然遇到问题,请检查你的代码并确保正确设置了 ZIP 条目。另外,还要注意防止尝试使用空的 ZIP 条目进行写入操作。 希望这能解决你的问题!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值