我运行一个单元测试来检查我的端点。当端点执行时,它将把日志写入日志目录。我想在单元测试完成后删除这个日志文件。但我收到以下异常:
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 操作系统中,其他用户正在使用的文件被锁定并且无法删除。 唯一的解决方案是在测试结束时关闭Reader(如果您正在使用它)。
或者直接迁移到 Linux 并忘记此类问题;)
编辑
显然关闭 LogManager 对他有用。
LogManager.shutdown()
关于java - 如何删除另一个线程正在使用的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54481017/