java 不使用 ant 解压 GBK 编码的 zip文件 (zip乱码问题)
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下有这个方法,直接调用;
这样就可以指定编码了;使用起来也简单!