Thang Pham
Thang Pham

Reputation: 38705

Java: File#reName() successfully rename the file, but the file object still reference the old name

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?

Upvotes: 4

Views: 2043

Answers (2)

Robin Green
Robin Green

Reputation: 33063

Yes, this is expected. File objects are immutable, and simply represent a filename.

You can think of it like this: a File object 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.txt to foo1.bak, then the original File variable that contained foo1.txt will still contain it, and can be used to open a FileOutputStream.

Upvotes: 4

Ted Hopp
Ted Hopp

Reputation: 234807

I believe it is expected. A File object is an abstraction of a path with respect to the underlying file system. It need not correspond to an existing file. The renameTo method moves the underlying file if it exists and if it is moveable. However, that does not change the path represented by the File object.

Upvotes: 1

Related Questions