我已按照中的说明进行操作这个线程 https://stackoverflow.com/questions/13787318/java-util-zip-replace-a-single-zip-file,使用其中的代码,我已经能够将文件添加到 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)中,对该文件夹的引用是 java .io.File 名为 transactionalProjectFolder,也是我的类的实例变量。但给了我这个错误:
应对来自:
C:\Dir1\Dir2\Dir3\存档结构的开始\存档结构的另一个文件夹副本\An Excel File.xlsm
到
\存档结构的开始\存档结构的另一个文件夹副本\Excel 文件.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.复制和 Files.move)存档内的文件,我已经被困在这个问题里一个月了,我不知道还能做什么,任何建议将不胜感激!
提前致谢! :)...