java - file.renameTo(newFile) 在 Java 中不起作用

标签 java file rename

我已经多次看到这个问题,但我还没有找到适合我的解决方案。我正在尝试将文件重命名为新文件名。我每次都变得错误,并且不确定为什么像大多数其他有同样问题的人一样。

我的代码如下:

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/

相关文章:

java - Admob 通过 Adwhirl : Not enough space to show ad! 想要 : 480, 75,有 : 480, 0

git - 为什么 Git 引用没有文件扩展名

c - 更新和删除文件内容

r - 当矩阵的维数未知时,如何设置唯一的行名和列名?

regex - 重命名多个文件,按 '_' 拆分文件名并保留第一个和最后一个字段

java - 如何使用除法将JLabel绑定(bind)到JSlider?

java - 如何将模型与 View 分离?

java - 调用 `new Date(long)` 结果是 "Jan 01 01:00:00 CET 1970"?

file - matlab输入n维数据需要什么格式?

linux - 文件内部批量重命名,包括子目录