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

标签 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)时打印的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/

相关文章:

java - 更新数据库后刷新JTable数据

arrays - 如何在 ruby​​ 中对文件名进行排序?

excel - 从 Excel 电子表格中的每一行创建文本文件

list - 用于删除列表中未指定的文件的 Powershell 脚本

c++ - remove() 函数删除所有其他文件

java - JDBC模板是否缓存连接?

java - 如何将 JBoss 服务器绑定(bind)到您的 Web 应用程序?

Java:接受字符串或整数输入

c++ - C++ 中的 cout、XOR 和 fileIO 格式化问题

python - Sublime Text : How to get the file name of the current view