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

时间:2018-10-24 14:39:18

标签: java file delete-file delete-directory

我正在努力解决以下问题:删除目录及其内容,然后再通过其他过程重新创建。

但是,似乎文件的句柄在删除过程中仍然保持打开状态,并导致在尝试重新创建时抛出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)时显示的堆栈跟踪:

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)

1 个答案:

答案 0 :(得分:0)

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

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);
}