0

I used the following code to rename a file and then get its new name:

File f1 = new File("C:/old.txt");
File f2 = new File("C:/new.txt");
System.out.println(f1.renameTo(f2));
System.out.println(f1.getName());

And the program returns

true
old.txt

renameTo() has succeeded, but why doesn't getName() return the new file name?

Gropai
  • 321
  • 1
  • 2
  • 11
  • I believe its that you're using f1 in get name. Or you could try to use a string for f2 – David Pulse Oct 15 '15 at 02:15
  • From the [`File` JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/io/File.html) - *"Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change"* – MadProgrammer Oct 15 '15 at 02:20
  • But if f1 has been renamed, why does getName() return the old name? – Gropai Oct 15 '15 at 02:20
  • Search the site and there's bound to be a duplicate. – Hovercraft Full Of Eels Oct 15 '15 at 02:23
  • Because, as MadProgrammer said, file objects are *immutable* and **never** change. – Hawkings Oct 15 '15 at 02:23
  • `File` is a "abstract representation" of a file/path, it doesn't actually have to point to a valid file/path. It represents the destination for other functionality, but until that functionality is executed, `File` can be anything. – MadProgrammer Oct 15 '15 at 02:25
  • Because the `File` class is misnamed. It represents a file *name*, including optional path, not the file itself. – Andreas Oct 15 '15 at 02:25

0 Answers0