假设需求是;将1.txt替换到Test.zip中test目录下。可以这样:
public static void main(String[] args)
{
Path myFilePath = Paths.get("C:\\Users\\Administrator\\Desktop\\1.txt");
Path zipFilePath = Paths.get("C:\\Users\\Administrator\\Desktop\\Test.zip");
try (FileSystem fs = FileSystems.newFileSystem(zipFilePath, null))
{
Path fileInsideZipPath = fs.getPath("\\test\\1.txt");
Files.copy(myFilePath, fileInsideZipPath, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e)
{
e.printStackTrace();
}
}
但期间发现,如果压缩包里路径有中文一直复制不成功,经调试发现路径上的中文都是乱码。最后发现编码格式是GBK,可能每种压缩包的编码格式都不一样吧QAQ
所以在打开压缩包时需要设置一下编码格式为GBK即可:
public static void main(String[] args)
{
Path myFilePath = Paths.get("C:\\Users\\Administrator\\Desktop\\1.txt");
Path zipFilePath = Paths.get("C:\\Users\\Administrator\\Desktop\\Test.zip");
//windows下需要设置一下字符集
Map<String, String> env = new HashMap<>();
env.put("encoding", "GBK");
try (ZipFileSystem fs = (ZipFileSystem) new ZipFileSystemProvider().newFileSystem(zipFilePath, env))
// try (FileSystem fs = FileSystems.newFileSystem(zipFilePath, null))
{
Path fileInsideZipPath = fs.getPath("\\test\\1.txt");
Files.copy(myFilePath, fileInsideZipPath, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException e)
{
e.printStackTrace();
}
}