4

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So to refresh the file reference, I need to File file = new File("test1.txt") again? Correct?
You should not specify the type again unless you want to create a new variable. So it should be file = new File ("test1.txt")
(Note File objects aren't that immutable. You can subclass them and override the methods to do all sorts of evil.)
Ambiguity of language. Objects whose class is java.io.File are immutable. But good point!
1

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.

2 Comments

So to refresh the file reference, I need to File file = new File("test1.txt") again? Correct?
@Harry - yes. As Robin said, a File object instance is immutable. If you want one that references the moved file, you need to create a new one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.