Java: File # reName () successfully renames a file, but the file object still refers to the old name

I am having weird behavior with Java

File file = new File("test.txt");
file.reName(new File("test1.txt"));

The file is successfully renamed from test.txtto 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 problem?

+3
source share
2 answers

Yes, it is expected. Fileobjects are immutable and just represent the file name.

You can think of it this way: an object Fileis a link to the file, not the file itself.

- , , , (.. ). foo1.txt foo1.bak, File, foo1.txt, - FileOutputStream.

+4

, . File . . renameTo , , . , File.

+1

All Articles