我们可以将文件
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*/);
简而言之:
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);
对于 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+,您应该查看并投票 kr37 的答案。
首先,创建一个 File 对象来表示目的地。检查该文件是否存在。如果不存在,则为要移动的文件创建一个新的 File 对象。对要移动的文件调用renameTo方法,并检查renameTo的返回值是否调用成功。
如果您想将一个文件的内容附加到另一个文件,有许多编写器可用。根据扩展名,听起来像是纯文本,所以我会查看 FileWriter。
通过将文件移动到新名称来重命名该文件。 (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();
}
这是重命名文件的简单方法:
File oldfile =new File("test.txt");
File newfile =new File("test1.txt");
if(oldfile.renameTo(newfile)){
System.out.println("File renamed");
}else{
System.out.println("Sorry! the file can't be renamed");
}
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);
试试这个
File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult
注: 我们应该始终检查 renameTo 返回值以确保重命名文件成功,因为它依赖于平台(不同的操作系统,不同的文件系统),并且如果重命名失败,它不会抛出 IO 异常。
是的,您可以使用 File.renameTo()。但在将其重命名为新文件时请记住具有正确的路径。
import java.util.Arrays;
import java.util.List;
public class FileRenameUtility {
public static void main(String[] a) {
System.out.println("FileRenameUtility");
FileRenameUtility renameUtility = new FileRenameUtility();
renameUtility.fileRename("c:/Temp");
}
private void fileRename(String folder){
File file = new File(folder);
System.out.println("Reading this "+file.toString());
if(file.isDirectory()){
File[] files = file.listFiles();
List<File> filelist = Arrays.asList(files);
filelist.forEach(f->{
if(!f.isDirectory() && f.getName().startsWith("Old")){
System.out.println(f.getAbsolutePath());
String newName = f.getAbsolutePath().replace("Old","New");
boolean isRenamed = f.renameTo(new File(newName));
if(isRenamed)
System.out.println(String.format("Renamed this file %s to %s",f.getName(),newName));
else
System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
}
});
}
}
}
如果只是重命名文件,可以使用 File.renameTo()。
如果您想将第二个文件的内容附加到第一个文件,请查看 带有附加构造函数选项的 FileOutputStream 或 FileWriter 的相同内容。您需要读取文件的内容以附加并使用输出流/编写器将其写出。
Files.move(file.toPath(), fileNew.toPath());
有效,但仅当您关闭(或自动关闭)所有使用的资源(
InputStream
、FileOutputStream
等)时,我认为与file.renameTo
或FileUtils.moveFile
的情况相同。
这是我成功重命名文件夹中多个文件的代码:
public static void renameAllFilesInFolder(String folderPath, String newName, String extension) {
if(newName == null || newName.equals("")) {
System.out.println("New name cannot be null or empty");
return;
}
if(extension == null || extension.equals("")) {
System.out.println("Extension cannot be null or empty");
return;
}
File dir = new File(folderPath);
int i = 1;
if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles()) {
try {
File newfile = new File(folderPath + "\\" + newName + "_" + i + "." + extension);
if(f.renameTo(newfile)){
System.out.println("Rename succesful: " + newName + "_" + i + "." + extension);
} else {
System.out.println("Rename failed");
}
i++;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
并运行它作为示例:
renameAllFilesInFolder("E:\\Downloads\\Foldername", "my_avatar", "gif");
我不喜欢
java.io.File.renameTo(...)
,因为有时它不会重命名文件,而你不知道为什么!它只是返回 true 或 false。如果失败,它不会抛出异常。
另一方面,
java.nio.file.Files.move(...)
更有用,因为它在失败时会抛出异常。
运行代码在这里。
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();
}
}
}