简体   繁体   English

NoSuchFileException使用Java NIO将文件添加到ZIP

[英]NoSuchFileException adding file to ZIP using Java NIO

I have a frustrating issue using the Java NIO to add files to existing ZIPs. 使用Java NIO将文件添加到现有ZIP时,我遇到了一个令人沮丧的问题。

On a test of 2500 files, 2 or 3 will fail. 在2500个文件的测试中,2或3将失败。 I am adding files to the root of the ZIP and not in a subfolder (which appears to be the source of some issues in other posts). 我将文件添加到ZIP的根目录而不是子文件夹中(该子文件夹似乎是其他帖子中某些问题的来源)。

The weird thing is that the file cited in the exception message it claims doesn't exist is neither the ZIP or the file being added, but the temporary file created by Java as it builds a new ZIP file. 奇怪的是,它声称不存在的异常消息中引用的文件既不是ZIP也不是要添加的文件,而是Java在构建新的ZIP文件时创建的临时文件。 Here is the code (less the try/catch): 这是代码(减去try / catch):

Map<String, String> zipProps = new HashMap<>();
zipProps.put("create", "false");
zipProps.put("encoding", "UTF-8");
FileSystem zipFs = null;

URI zipAsFileSys = new URI("jar", fileToArchive.toURI().toString(), null);
zipFs = FileSystems.newFileSystem(zipAsFileSys, zipProps);
Path pathToNewFileInZip = zipFs.getPath(fileIdFile.getName());
Path pathToNewFileOnDisk = Paths.get(fileIdFile.getAbsolutePath());
Files.createFile(pathToNewFileInZip ); //Added later. No difference.
Files.copy(pathToNewFileOnDisk, pathToNewFileInZip, StandardCopyOption.REPLACE_EXISTING);
if(zipFs!=null) zipFs.close(); 

And the exception: 和例外:

Exception: java.nio.file.NoSuchFileException: \\Server\archives\zipfstmp7224673021628877485.tmp

This was ultimately traced to network latency and/or Windows caching when manipulating files on a remote drive. 最终,这可追溯到操作远程驱动器上的文件时的网络延迟和/或Windows缓存。

Seems Java can't figure out that the file it just created actually exists. 似乎Java无法确定它刚刚创建的文件确实存在。 It would be nice if it was possible to get a handle on the tmp file to see if it exists. 如果可以在tmp文件上获取一个句柄以查看它是否存在,那将是很好的。

Seeing as I don't have the ability to mess with the OS caching, I never found a good workaround other than introducing a delay before the Files.copy(...) call, and because our production environment doesn't use multiple servers for this exact task, it isn't stopping me from proceeding. 看到我没有搞乱操作系统缓存的能力,除了在Files.copy(...)调用之前引入延迟外,而且因为我们的生产环境没有使用多台服务器,所以我从未找到一种好的解决方法对于这项确切的任务,这并没有阻止我继续前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM