使用 Java 重命名文件

新手上路,请多包涵

我们可以重命名文件 test.txttest1.txt 吗?

如果 test1.txt 存在,它会重命名吗?

如何将其重命名为现有的 test1.txt 文件,以便将 test.txt 的新内容添加到其中供以后使用?

原文由 Shekhar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 666
1 个回答

复制自 http://exampledepot.8waytrips.com/egs/java.io/RenameFile.html

 // File (or directory) with old name
File file = new File("oldname");

// File (or directory) with new name
File file2 = new File("newname");

if (file2.exists())
   throw new java.io.IOException("file exists");

// Rename file (or directory)
boolean success = file.renameTo(file2);

if (!success) {
   // File was not successfully renamed
}

附加到新文件:

 java.io.FileWriter out= new java.io.FileWriter(file2, true /*append=yes*/);

原文由 Pierre 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题