java - 使用 Java 重命名文件

标签 java file rename file-rename

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

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

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

最佳答案

复制自 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*/);

关于java - 使用 Java 重命名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1158777/

相关文章:

java - JNI 失去对 native 方法的引用

android - 如何访问手机或SD卡内存中的文件

python - 当url不变时如何使用python下载文件

php - 如何在 symfony 中重命名一个包?

C++:使用同步时重命名而不是删除和复制

java - 如何在 Spring 上配置 SSL/HTTPS?

java - 在文件上传时信任 "Content-Type"

java - 将 Java 应用程序转变为 Servlet

windows - 文件创建时间的准确性是多少?

甲骨文 :Are grants removed when an object is dropped?