I experienced a strange behavior from Java
File file = new File("test.txt");
file.reName(new File("test1.txt"));
The file successfully rename from test.txt to test1.txt, but if I do
System.out.println(file.getCanonicalPath()); //This return test.txt
Is this expected? And what is a clean way to solve this?
Yes, this is expected.
Fileobjects are immutable, and simply represent a filename.You can think of it like this: a
Fileobject is a reference to a file, not the file itself.This behaviour can actually be useful – for example, imagine that you are moving a previous version of a file out of the way to avoid overwriting it (i.e. to create a backup copy). If you rename
foo1.txttofoo1.bak, then the originalFilevariable that containedfoo1.txtwill still contain it, and can be used to open aFileOutputStream.