File oldFile = new File("old");
if (oldFile.renameTo(new File("new"))){
System.out.println(oldFile.getName());//this prints "old"
}
我查看了openJDK的源代码,其中renameTo(File dest)函数的代码如下:
public class File implements Serializable, Comparable<File> {
static private FileSystem fs = FileSystem.getFileSystem();
private String path;
...
public boolean renameTo(File dest) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
security.checkWrite(dest.path);
}
return fs.rename(this, dest);
}
...
}
所以路径变量永远不会改变。为什么会这样?正确使用重命名的文件变量的方法是什么?目前我是这样做的:File oldFile = new File("/home/blin/misk/old");
File newFile = new File("/home/blin/misk/new");
if (oldFile.renameTo(newFile)){
oldFile=newFile;
System.out.println(oldFile.getName());//this prints "new"
}