java - 将文件添加到 zip 文件 java 中的文件夹

标签 java zip nio

我正在尝试将 txt 文件添加到 zip 文件内的文件夹中。 首先,我提取 zip 文件的所有内容,然后添加 txt 文件,然后再压缩回来。 然后我阅读了 nio 方法,我可以在不解压缩的情况下修改 zip。使用这种方法,我可以将 txt 文件添加到 zip 的主文件夹中,但我不能更深入。

testing.zip 文件中有 res 文件夹。

这是我的代码:

        Path txtFilePath = Paths.get("\\test\\prefs.txt");
        Path zipFilePath = Paths.get("\\test\\testing.zip");
        FileSystem fs;
        try {
            fs = FileSystems.newFileSystem(zipFilePath, null);
            Path fileInsideZipPath = fs.getPath("res/prefs.txt");  //when I remover "res/" code works.
            Files.copy(txtFilePath, fileInsideZipPath);
            fs.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

我得到以下异常:

java.nio.file.NoSuchFileException: res/

最佳答案

(编辑给出实际答案)

做:

fs.getPath("res").resolve("prefs.txt")

代替:

fs.getPath("res/prefs.txt")

.resolve() 方法将在文件分隔符等方面做正确的事情。

关于java - 将文件添加到 zip 文件 java 中的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17083662/

相关文章:

连续更改 map 大小时,Java MappedByteBuffer 性能越来越差

java - 与嵌套 Parens 的正则表达式匹配

java - Wicket:如何将 DropDownChoice 与 PropertyModel 一起使用?

java - eclipse -> 代码模板 有哪些可用变量?

python - Zipfile python模块字节大小差异

tomcat - 如何将 POST 数据从 servlet 读取到 ZipStream?

java - 文件逐行写入

java - 如何在 Java 中使用自定义类型注解

c - 使用 Minizip 查找未压缩的数据

java - 如何等待并锁定文件