【发布时间】:2019-06-18 18:38:25
【问题描述】:
我正在尝试将文件目录添加到 zip。该目录大约有 150 个文件。在几个 5-75 个文件中,我不断崩溃并显示错误消息 "The process cannot access the file because it is being used by another process."
我尝试了延迟,这可能会有所帮助,但肯定不能解决错误。
使用以下代码: Is it possible to create a NEW zip file using the java FileSystem?
final File folder = new File("C:/myDir/img");
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
continue;
}
else {
String filename = fileEntry.getName();
String toBeAddedName = "C:/myDir/img/" + filename;
Path toBeAdded = FileSystems.getDefault().getPath(toBeAddedName).toAbsolutePath();
createZip(zipLocation, toBeAdded, "./" + filename);
System.out.println("Added file " + ++count);
//Delay because 'file in use' bug
try { Thread.sleep(1000); } //1secs
catch (InterruptedException e) {}
}
}
public static void createZip(Path zipLocation, Path toBeAdded, String internalPath) throws Throwable {
Map<String, String> env = new HashMap<String, String>();
//Check if file exists.
env.put("create", String.valueOf(Files.notExists(zipLocation)));
//Use a zip filesystem URI
URI fileUri = zipLocation.toUri(); //Here
URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);
System.out.println(zipUri);
//URI uri = URI.create("jar:file:"+zipLocation); //Here creates the zip
//Try with resource
try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
//Create internal path in the zipfs
Path internalTargetPath = zipfs.getPath(internalPath);
//Create parent dir
Files.createDirectories(internalTargetPath.getParent());
//Copy a file into the zip file
Files.copy(toBeAdded, internalTargetPath, StandardCopyOption.REPLACE_EXISTING);
}
}
【问题讨论】:
-
如果文件因为正在使用而被锁定,除了向用户显示一条消息并要求他们更正之外,我看不出还有什么可以做的。
-
@markspace 锁定文件的是应用程序本身。这就是我尝试添加延迟的原因。
-
我现在在文件之间使用两秒钟的延迟,恕我直言,它很大但它正在工作。
-
如果可以阻止进程删除它本身已锁定的文件,我会觉得很奇怪(但我可能是错的)。您确定没有其他进程正在锁定文件吗?错误消息将表明是这种情况。你可以检查一下;例如,请参阅 this question (windows) 或 this question (linux)。
-
您是否有可能将 zip 添加到自身?
标签: java filesystems zip zipfile