62,633
社区成员




renameTo
public boolean renameTo(File dest)重新命名此抽象路径名表示的文件。
此方法行为的许多方面都是与平台有关的:重命名操作无法将一个文件从一个文件系统移动到另一个文件系统,该操作不是不可分的,如果已经存在具有目标抽象路径名的文件,那么该操作可能无法获得成功。应该始终检查返回值,以确保重命名操作成功。
参数:
dest - 指定文件的新抽象路径名
返回:
当且仅当重命名成功时,返回 true;否则返回 false
File file = new File(fileName);
File newFile = new File(fileName.replace("2008", "2011"));
BufferedReader bReader = new BufferedReader(new FileReader(file));
PrintWriter pWriter = new PrintWriter(newFile.getPath());
String linesString = "";
if (!file.exists()) {
throw new RuntimeException("文件不存在");
}else{
while((linesString = bReader.readLine())!=null){
System.out.println(linesString.replace("2008-", "2009-"));
}
bReader.close();
pWriter.close();
}
if(file.renameTo(newFile)){
System.out.println("Rename file succeed");
}else {
System.out.println("Rename file failed");
}
}
File f1 = new File("c:/error.txt");
File f2 = new File("c:/error1.txt");
if(f2.exists()){
f2.delete();
}
System.out.println(f2.exists());
boolean b = f1.renameTo(f2);
System.out.println(b);