我已经多次看到这个问题,但我还没有找到适合我的解决方案。我正在尝试将文件重命名为新文件名。我每次都变得错误,并且不确定为什么像大多数其他有同样问题的人一样。
我的代码如下:
File file = new File("filePath.log");
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
for(int i = 1 ; i < 300 ; i++){
bw.write(i);
if(i % 100 == 0){
File newFile = new File("filePath2.log");
if(file.renameTo(newFile)){
System.out.println("true");
} else{
System.out.println("false");
}
file = new File("filePath.log");
bw = new BufferedWriter(new FileWriter(file));
}
}
感谢任何帮助!
编辑:
我能够使用 Files.move 方法解决问题
bw.close();
String newFilePath ="C:/opt/streamserve/projroot/applications/RFC_SAP_T1/wd/rfcgateway07122014" + move + ".log";
File newFile = new File(newFilePath);
Files.move(file.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
file = new File("C:/opt/streamserve/projroot/applications/RFC_SAP_T1/wd/rfcgateway.log");
fw = new FileWriter(file);
bw = new BufferedWriter(fw);
move++;
最佳答案
在 Windows 上,打开的文件被隐式锁定。如果您不想要此功能,请不要使用 Windows(我假设您可以通过 hack 来避免这种情况发生)
问题是您无法重命名已锁定的文件。在 Unix 下,文件只有在您明确执行此操作时才会被锁定,在 Windows 中,只需打开文件即可锁定。
解决方案总是在尝试重命名文件之前关闭文件,即使在 Unix 上也是一种很好的做法。
关于java - file.renameTo(newFile) 在 Java 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25022924/