java - 在 Java 中重命名文件的正确方法是什么?

标签 java file cross-platform

我所说的“正确”文件重命名是什么意思:

  1. 它应该适用于不同的平台。

  2. 它应该以某种方式处理以下情况:

    1. 文件已锁定
    2. 名称为"new"的文件已经存在
    3. 磁盘上没有足够的可用空间来完成操作。

是否有任何通用的解决方案/库/策略?

最佳答案

如 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/

相关文章:

java - 文件传输陷入 do while 循环

android - 带有图像和文本的按钮以及图像下方的文本,如何?

java - 如何将字符串列表映射到空列表?

java - 如何将数组和字符串一起保存到一个紧凑的包中

java - 通过 DataInputStream 连续读取套接字消息的正确方法是什么?

java - 不兼容的类型 - 在 java 中找到了 java.lang.String 但预期为 int

python - 返回两个文件之间不同的行 (Python)

python - 将包含 0's and 1' 的列表转换为位数组(使用位数组模块)并输出到二进制文件错误

c - 有没有不支持 ANSI C 89 的平台?

c++ - 将压缩文件嵌入到 C++ 程序中