java 不使用 ant 解压 GBK 编码的 zip文件 (zip乱码问题)

Java在解压GBK编码的ZIP文件时可能出现乱码,由于ZIP文件本身编码未指定,Windows使用GBK,而Java默认UTF-8。通过分析Java NIO的ZipFileSystem,可以找到指定编码的解决方法,避免依赖Ant,提高效率。

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

  Java解压zip有时会导致乱码,是应为zip缺陷,没有指定编码,windows中文环境下为GBK,日文环境下是JIS,linux编码为UTF-8,而Java使用UTF-8,Java默认的ZipFile也不能指定编码,每次为了兼容不得不去依赖Ant,但是只为了解压缩完全不合算,今天看nio源码时发现了一个解决方案:

String file = "/home/tao/下载/录用函.zip";
String toPath = "/home/tao/下载";

Path path = Paths.get(file);
Map<String,String> env = new HashMap<>();
env.put("encoding","GBK");
ZipFileSystem zipFileSystem  = (ZipFileSystem) new ZipFileSystemProvider().newFileSystem(path,env);

Files.walkFileTree(zipFileSystem.getPath("/"),new SimpleFileVisitor<Path>(){
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        System.out.println(file.toString());
        Path destPath = Paths.get(toPath, file.toString());
        Files.deleteIfExists(destPath);
        Files.createDirectories(destPath.getParent());
        Files.move(file, destPath);
        return  FileVisitResult.CONTINUE;
    }
});

分析:

在ZIpFileSystem下有如下字段,顾名思义肯定是编码,

private final ZipCoder zc;
private final String defaultDir;
private final String nameEncoding;

find引用,找到了设置地址

ZipFileSystem(ZipFileSystemProvider var1, Path var2, Map<String, ?> var3) throws IOException {
    this.createNew = "true".equals(var3.get("create"));
    this.nameEncoding = var3.containsKey("encoding") ? (String)var3.get("encoding") : "UTF-8";
    this.useTempFile = Boolean.TRUE.equals(var3.get("useTempFile"));
    this.defaultDir = var3.containsKey("default.dir") ? (String)var3.get("default.dir") : "/";
    

得传一个encoding 到map中去,不然就设置为utf-8了

but,并没有如下方法

FileSystems.newFileSystem(Path path,Map env);

把path转换为URI又报错

debug时发现只要具体地址不为“/"就抛错误:完全不懂了,不能传地址进去???还望大佬告知!!!

幸好ZipFileSystem下有这个方法,直接调用;

这样就可以指定编码了;使用起来也简单!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值