我们能把test。txt重命名为test1.txt吗?
如果test1.txt存在,它会重命名吗?
如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?
我们能把test。txt重命名为test1.txt吗?
如果test1.txt存在,它会重命名吗?
如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?
当前回答
简而言之:
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中重命名文件,请参阅file类中renameTo()方法的文档。
试试这个
File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult
注意: 我们应该总是检查renameTo返回值,以确保重命名文件成功,因为它依赖于平台(不同的操作系统,不同的文件系统),如果重命名失败,它不会抛出IO异常。
对于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()。但是,在将其重命名为新文件时,请记住要有正确的路径。
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 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");
}