我们能把test。txt重命名为test1.txt吗?

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

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


当前回答

对于Java 1.6及以下版本,我相信最安全、最干净的API是Guava的Files.move。

例子:

File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());

第一行确保新文件的位置是相同的目录,即旧文件的父目录。

编辑: 我是在开始使用Java 7之前写的这篇文章,Java 7引入了非常类似的方法。所以如果你正在使用Java 7+,你应该看到并投票kr37的答案。

其他回答

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

如果只是重命名文件,可以使用file . renameto()。

如果您希望将第二个文件的内容附加到第一个文件,请使用附加构造函数选项查看FileOutputStream或FileWriter。您需要读取文件的内容来追加,并使用输出流/写入器将它们写出来。

我不喜欢java.io.File.renameTo(…),因为有时它不重命名文件,你不知道为什么!它只返回true (false)如果失败,它不会抛出异常。

另一方面,java.nio.file.Files.move(…)更有用,因为它会在失败时抛出异常。

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.*;

Path yourFile = Paths.get("path_to_your_file\text.txt");

Files.move(yourFile, yourFile.resolveSibling("text1.txt"));

使用实例替换一个名为“text1.txt”的文件。

Files.move(yourFile, yourFile.resolveSibling("text1.txt"),REPLACE_EXISTING);

对于Java 1.6及以下版本,我相信最安全、最干净的API是Guava的Files.move。

例子:

File newFile = new File(oldFile.getParent(), "new-file-name.txt");
Files.move(oldFile.toPath(), newFile.toPath());

第一行确保新文件的位置是相同的目录,即旧文件的父目录。

编辑: 我是在开始使用Java 7之前写的这篇文章,Java 7引入了非常类似的方法。所以如果你正在使用Java 7+,你应该看到并投票kr37的答案。