如何删除另一个线程正在使用的文件?

How to delete a file that is being used by another thread?

我 运行 一个检查我的端点的单元测试。当端点执行时,它会将日志写入日志目录。我想在单元测试完成后删除这个日志文件。但是我得到以下异常:

 java.nio.file.FileSystemException: C:\Users\dev\IdeaProjects\users\src\main\resources\log\events The process cannot access the file, as this file is being used by another process.

我有以下方法:

public static void deleteLogDir() throws IOException {
     String logEventPath = System.getProperty("user.dir") +  "/users/src/main/resources/log/events";
     Path path = Paths.get(logEventPath);
     Files.list(path).forEach(e -> {
            try {
                  Files.deleteIfExists(e);
                } catch (IOException e1) {
                   e1.printStackTrace();
                }
     });
}


@AfterAll
public static void clear() throws IOException {
     deleteLogDir();
}

我没有在任何其他程序中打开此文件。当我试图从 test/java 目录中删除 main/java 中的这个文件时,它被毫无问题地删除了。当我什至尝试从测试目录中的这个文件中读取时,我得到 java.nio.file.AccessDeniedException。

如何删除这个日志文件?

在 Windows OS 中,其他用户正在使用的文件 已锁定 且无法删除。 唯一的解决方案是在测试结束时关闭 Reader,如果您正在使用它的话。

或者只是移动到 Linux 而忘记这类问题 ;)

编辑

显然关闭 LogManager 对他有用。 LogManager.shutdown()