我所说的“正确”文件重命名是什么意思:
它应该适用于不同的平台。
它应该以某种方式处理以下情况:
- 文件已锁定
- 名称为"new"的文件已经存在
- 磁盘上没有足够的可用空间来完成操作。
是否有任何通用的解决方案/库/策略?
最佳答案
如 javadoc 中所述:
Renames the file denoted by this abstract pathname. Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
这是一个例子:
// The File (or directory) with the old name
File oldFile = new File("old.txt");
// The File (or directory) with the new name
File newFile = new File("new.txt");
// Rename file (or directory)
boolean success = oldFile.renameTo(newFile);
if (!success) {
// File was not successfully renamed
}
我的建议是检查 success
boolean 值并使用 API 中定义的标准方法。
关于java - 在 Java 中重命名文件的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6813939/