1

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

但是,似乎文件的句柄仍被删除过程保持打开状态,并导致在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.
}

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

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)
4

1 回答 1

0

The trouble is in this part of your code:

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

Unfortunately, Files.list(Path) puts some sort of lock on the directory. Here's a workaround for you:

Stream<Path> list = Files.list(parentDir);
int count = list.count();
list.close();
if (0 == count) {
    Files.delete(parentDir);
}
于 2019-08-01T21:27:53.543 回答