Java文件重命名
文件重命名是常遇到的問題,下面就用實例的形式展現如何進行文件重命名:
import java.io.File;
public class RenameFile {
public static void main(String[] args) {
// TODO Auto-generated method stub
String path="E:\\娛樂";
String oldName="JavaTest";
String newName="JavaTest1";
rename(path,oldName,newName);
System.out.println("重命名成功");
}
private static void rename(String path, String oldName, String newName) {
if(!oldName.equals(newName)){
File oldFile=new File(path+"/"+oldName);
File newFile=new File(path+"/"+newName);
if(!oldFile.exists()){
return;
}
if(newFile.exists()){
System.out.println(newName+" 已存在");
}
else {
oldFile.renameTo(newFile);
}
}else {
System.out.println("新文件名和舊文件名相同。。。");
}
}
}