1.直接上代码:
import java.io.File;
import java.io.IOException;
public class Realname {
public static void main(String[] args) {
updateName("syp");
}
//修改文件名
public static void updateName(String fileType){
File oldFile = new File("E:"+ File.separator +""+fileType+"1.txt");
if (!oldFile.exists()) {
try {
oldFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("修改前文件名称是:" + oldFile.getName());
String rootPath = oldFile.getParent();
System.out.println("获取到的根路径是:" + rootPath);
File newFile = new File(rootPath + File.separator + ""+fileType+".txt");
System.out.println("最后修改的文件名称是:" + newFile.getName());
if (oldFile.renameTo(newFile)) {
System.out.println("修改成功!");
} else {
System.out.println("修改失败");
}
}
}
2.效果图:
①修改之前:
②修改之后: