file.renameTo避坑:
- renameTo成功后,旧文件不存在了,若renameTo返回失败,旧文件还在
- 不管是否renameTo成功,原内存中oldFile对象的path属性没变,若旧文件不存在了,继续访问文件会异常,需要使用新的newFile对象继续访问文件
- renameTo的新路径文件如果已经存在,则renameTo会失败,新老文件都不变
测试代买demo:
import java.io.File;
import java.io.IOException;
public class TestFileRenameTo {
public static void main(String[] args) {
//String dir = "D:\\luoyonghong1\\Desktop\\myweb\\src\\main\\resources";
String oldPath = "old.txt";
String newPath = "new.txt";
File oldFile = new File(oldPath);
if (!oldFile.isFile()) {
try {
oldFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//调用renameTo()前
System.out.println("renameTo之前的oldFile的path:" + oldFile.getAbsolutePath());
File newFile = new File(newPath);
boolean success = oldFile.renameTo(newFile);
if (success) {
System.out.println("第一次renameTo执行成功,oldFile对象的path:" + oldFile.getAbsolutePath() + ",newFile对象的path:" + newFile.getAbsolutePath());
//renameTo成功,旧文件不在,继续访问会抛异常
System.out.println("旧文件是否存在:" + oldFile.exists());
System.out.println("旧文件是否可读:" + oldFile.canRead());
} else {
System.out.println("第一次renameTo失败");
}
//newPath路径的文件已经存在,renameTo会失败
boolean success2 = oldFile.renameTo(newFile);
if (success2) {
System.out.println("第二次renameTo执行成功,oldFile对象的path:" + oldFile.getPath() + "\nnewFile对象的path:" + newFile.getPath());
} else {
System.out.println("第二次renameTo失败");
}
}
}