使用 Java 重命名文件

2022-08-31 06:10:21

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

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

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


答案 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*/);

答案 2

总之:

Files.move(source, source.resolveSibling("newname"));

更多详情:

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

以下内容直接从 http://docs.oracle.com/javase/7/docs/api/index.html 复制:

假设我们要将一个文件重命名为“newname”,将该文件保留在同一目录中:

Path source = Paths.get("path/here");
Files.move(source, source.resolveSibling("newname"));

或者,假设我们要将文件移动到新目录,保留相同的文件名,并替换目录中该名称的任何现有文件:

Path source = Paths.get("from/path");
Path newdir = Paths.get("to/path");
Files.move(source, newdir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);