带有REPLACE_EXISTING选项的FileAlreadyExistsException

J R*_*bes 10 java exception file move

在我的代码中,有一个循环用另一个文件替换文件.

这完成了:

java.nio.file.Files.move(Path source, Path target, CopyOption... options) throws IOException
Run Code Online (Sandbox Code Playgroud)

抛出以下异常:

Exception in thread "main" java.nio.file.FileAlreadyExistsException: C:\BRUTE-FORCE\Test-Loads-2-forces-only.dat.temp -> C:\BRUTE-FORCE\Test-Loads-2-forces-only.dat
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsFileCopy.move(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.move(Unknown Source)
    at java.nio.file.Files.move(Unknown Source)
(*) at bruteforce.Main.changeValue(Main.java:260)
    at bruteforce.Main.main(Main.java:71)
Run Code Online (Sandbox Code Playgroud)

抛出异常的行:

(*) at bruteforce.Main.changeValue(Main.java:260):

Files.move(path, path.resolveSibling("DESTINY_FILE"), REPLACE_EXISTING);
Run Code Online (Sandbox Code Playgroud)

Javadoc定义了异常:

...
FileAlreadyExistsException - if the target file exists but cannot be replaced because the REPLACE_EXISTING option is not specified (optional specific exception) 
...
Run Code Online (Sandbox Code Playgroud)

代码清楚地指定了REPLACE_EXISTING.

此选项也会在文件开头导入:

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
Run Code Online (Sandbox Code Playgroud)

任何提示?

这可能是由于计算机(或HDD)的hybernates或类似的东西?我在使用电网时设置了能量选项而不是暂停.

提前致谢

Wil*_*Owl 3

Files.move 不是原子操作(当然除非指定了 ATOMIC_MOVE),所以我假设发生的是其他一些 IO 锁定了该文件。

请确保您:

  • 在此资源上的午餐close()方法或使用try-with-resources

  • 您的操作系统没有使用此文件(例如,在记事本中打开,您午餐 反对它)

如果您的文件经常被访问,那么您可以尝试创建循环来检查 Files.isWritable()