我们能把test。txt重命名为test1.txt吗?
如果test1.txt存在,它会重命名吗?
如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?
我们能把test。txt重命名为test1.txt吗?
如果test1.txt存在,它会重命名吗?
如何将其重命名为已经存在的test1.txt文件,以便将test.txt的新内容添加到其中以供以后使用?
当前回答
Files.move(file.toPath(), fileNew.toPath());
工作,但只有当你关闭(或自动关闭)所有使用的资源(InputStream, FileOutputStream等),我认为文件的情况相同。renameTo或FileUtils.moveFile。
其他回答
据我所知,重命名文件不会将其内容附加到具有目标名称的现有文件中。
关于在Java中重命名文件,请参阅file类中renameTo()方法的文档。
这是一个简单的重命名文件的方法:
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");
}
试试这个
File file=new File("Your File");
boolean renameResult = file.renameTo(new File("New Name"));
// todo: check renameResult
注意: 我们应该总是检查renameTo返回值,以确保重命名文件成功,因为它依赖于平台(不同的操作系统,不同的文件系统),如果重命名失败,它不会抛出IO异常。
通过将文件移动到新名称来重命名文件。(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();
}
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);