gpt4 book ai didi

java - 删除并重新创建文件/目录

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:35 24 4
gpt4 key购买 nike

我正在努力解决一个问题,即目录及其内容被删除,然后由不同的进程重新创建。

但是,似乎该文件的句柄在删除过程中仍然保持打开状态,并导致在尝试重新创建时引发 AccessDeniedException。任何帮助将不胜感激。示例代码如下:

private static void deleteFilesAndDirectories(Path targetPath, Predicate<? super Path> filter) {
try {
try (Stream<Path> eligibleFiles = Files.walk(targetPath)
.filter(path -> !Files.isDirectory(path))
.filter(filter)) {

for (Path file : eligibleFiles.collect(Collectors.toList())) {
if (Files.isDirectory(file)) {
deleteFilesAndDirectories(file, filter);
}

Path parentDir = file.getParent();
Files.delete(file);

//Delete holding directory
if (Files.list(parentDir).count() == 0) {
Files.delete(parentDir);
}
}
}

} catch (IOException e) {
logger.error("Failed to delete directory"); //AccessDeniedException is caught
}
}

public static void delete(String subdirectory) {
deleteFilesAndDirectories(Paths.get(subdirectory), path -> true);
}

public static void store(MultipartFile file, String subdirectory) {
Path subdirectoryPath = Paths.get(subdirectory);

if (!Files.isDirectory(subdirectoryPath)) {
try {
Files.createDirectories(subdirectoryPath);

} catch (IOException e) {
throw new StorageException("Could not create sub-directory " + subdirectoryPath.toAbsolutePath(), e);
}
}

public static void main(String[] args) {
MultipartFile file = ...;

delete("mydir"); //Attempts to delete directory, but is still visible in Windows Explorer though access is denied when trying to go into it

store(file, "mydir"); //Checks if directory already exists, and attempts to create if not there.
}

执行Files.createDirectories(subdirectoryPath)时打印的Stacktrace:

Caused by: java.nio.file.AccessDeniedException: D:\Workspaces\***\application\pending\0
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:83)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.createDirectory(WindowsFileSystemProvider.java:504)
at java.nio.file.Files.createDirectory(Files.java:674)
at java.nio.file.Files.createAndCheckIsDirectory(Files.java:781)
at java.nio.file.Files.createDirectories(Files.java:767)

最佳答案

问题出在代码的这一部分:

if (Files.list(parentDir).count() == 0) {
Files.delete(parentDir);
}

不幸的是,Files.list(Path) 对目录设置了某种锁定。这是适合您的解决方法:

Stream<Path> list = Files.list(parentDir);
int count = list.count();
list.close();
if (0 == count) {
Files.delete(parentDir);
}

关于java - 删除并重新创建文件/目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52971766/

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