我们能把test。txt重命名为test1.txt吗?
如果test1.txt存在,它会重命名吗?
如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?
我们能把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的答案。
其他回答
您希望在File对象上使用renameTo方法。
首先,创建一个File对象来表示目的地。检查该文件是否存在。如果它不存在,为要移动的文件创建一个新的File对象。在要移动的文件上调用renameTo方法,并检查renameTo的返回值,以查看调用是否成功。
如果要将一个文件的内容附加到另一个文件,有许多可用的写入器。基于扩展,它听起来像是纯文本,所以我会看看FileWriter。
摘自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*/);
简而言之:
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);
运行代码在这里。
private static void renameFile(File fileName) {
FileOutputStream fileOutputStream =null;
BufferedReader br = null;
FileReader fr = null;
String newFileName = "yourNewFileName"
try {
fileOutputStream = new FileOutputStream(newFileName);
fr = new FileReader(fileName);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
fileOutputStream.write(("\n"+sCurrentLine).getBytes());
}
fileOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
通过将文件移动到新名称来重命名文件。(FileUtils来自Apache Commons IO lib)
String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), "") + newName;
File newFile = new File(newFilePath);
try {
FileUtils.moveFile(oldFile, newFile);
} catch (IOException e) {
e.printStackTrace();
}