gpt4 book ai didi

java - 在 zip 中写入(修改或添加)文件

转载 作者:行者123 更新时间:2023-11-30 11:36:11 25 4
gpt4 key购买 nike

我已按照说明进行操作 this thread ,使用那里的代码我已经能够将文件添加到 zip 文件而无需解压缩和重新压缩它,但是我有一个问题,让我给你看我的代码:

private void saveFileIntoProjectArchive(Path pathOfFile) {
this.projectArchiveFile.setWritable(true, false);
Path zipFilePath = Paths.get(this.projectArchiveFile.getAbsolutePath()),
pathToSaveInsideZIP = null;
FileSystem fs;
try {
fs = FileSystems.newFileSystem(zipFilePath, null);
pathToSaveInsideZIP = fs.getPath(pathOfFile.toString().substring((int) this.transactionalProjectFolder.getAbsolutePath().length()));
System.out.println("Coping from:\n\t"+pathOfFile+"\nto\n\t"+pathToSaveInsideZIP);
Files.copy(pathOfFile, pathToSaveInsideZIP, REPLACE_EXISTING);
System.out.println("Done!!!");
fs.close();
} catch (java.nio.file.NoSuchFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
projectArchiveFile.setWritable(false, false);
}

我想做的是,我有同一个项目的许多文件,该项目是一个存档(ZIP,在代码中由名为 projectArchiveFile 的 java.io.File 引用,我的实例变量类)包含所有这些文件,当我想使用我的存档中的某些文件时,我只将该文件解压缩到一个结构与我的存档中的文件夹(ZIP,projectArchiveFile)相同的文件夹中,对该文件夹的引用是一个名为transactionalProjectFolder的java.io.File,也是我类的一个实例变量。但是给我这个错误:

应对来自: C:\Dir1\Dir2\Dir3\Begin of Archive stucur\Another folder replica of the archive structure\An Excel File.xlsm 存档结构的另一个文件夹副本到 \存档结构的开始\存档结构的另一个文件夹副本\An Excel File.xlsm

java.nio.file.NoSuchFileException: Begin of Archive stucure\Another folder replica of the archive structure\ at com.sun.nio.zipfs.ZipFileSystem.checkParents(ZipFileSystem.java:846)
at com.sun.nio.zipfs.ZipFileSystem.newOutputStream(ZipFileSystem.java:515)
at com.sun.nio.zipfs.ZipPath.newOutputStream(ZipPath.java:783)
at com.sun.nio.zipfs.ZipFileSystemProvider.newOutputStream(ZipFileSystemProvider.java:276)
at java.nio.file.Files.newOutputStream(Files.java:170)
at java.nio.file.Files.copy(Files.java:2826)
at java.nio.file.CopyMoveHelper.copyToForeignTarget(CopyMoveHelper.java:126)
at java.nio.file.Files.copy(Files.java:1222)

堆栈跟踪的其余部分是我的类。

我已经能够在存档 (zip) 的根目录中写入,但是每当我尝试在存档 (zip) 内部的文件夹中写入时,它都会失败,正如您在堆栈跟踪中注意到的那样,它说 java.nio.file.NoSuchFileException: Begin of Archive stucure\Another folder replica of the archive structure\ 如果我要复制的文件,它会在名称之前停止,我完全确定 zip 中的路径存在并且拼写正确它只是不想写(我尝试使用 Files.copy 和 Files.move)存档中的文件,我一直被困在这一个月,我不知道还能做什么,任何建议将不胜感激!!!

提前致谢! :)...

最佳答案

即使您确定该路径存在,我也会为了故障排除添加下面的行并查看它创建的目录结构。

错误表明 zip 中缺少目录。可能是您使用了一些 zip 等不支持的奇怪文件夹名称。

System.out.println("Coping from:\n\t"+pathOfFile+"\nto\n\t"+pathToSaveInsideZIP);

Files.createDirectories(pathToSaveInsideZIP); // add this row

Files.copy(pathOfFile, pathToSaveInsideZIP, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Done!!!");

关于java - 在 zip 中写入(修改或添加)文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14647152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com