一尘不染

使用Java重命名文件

java

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

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

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


阅读 454

收藏
2020-03-01

共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*/);
2020-03-01