我们可以将文件重命名为 test.txt
为 test1.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/