• Post Reply Bookmark Topic Watch Topic
  • New Topic

immutability of java.io.File  RSS feed

 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
According the API, "Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change." How exactly does work with the File instance method renameTo(File)? Doesn't that change the abstract pathname?

Thank you,
Yuriy
 
Joe Ess
Bartender
Posts: 9439
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
File does not necessarily need to point to an existing path (hence the exists() method). Using renameTo() does not change that instance's absolute path. It remains the same. You would need to create a new instance to point to the renamed file.
 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmm, so if you rename a File (on an OS where this moves the physical file) and then try to write to it, you will create a file at the existing location? I didn't know that. Thanks!

Yuriy
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Joe]: You would need to create a new instance to point to the renamed file.

In fact you need to create a new instance to refer to the new name of the file, before you do the rename. Because renameTo() takes a File as an argument. So:

If it helps to understand this, remember that a File typically does not represent an actual file so much as a file name (including the path). Only one file exists in this example, but two different File objects refer to it.

[Yuriy]: Hmm, so if you rename a File (on an OS where this moves the physical file) and then try to write to it, you will create a file at the existing location?

This has nothing to do with writing to the file - we're just talking about the effect of renameTo() so far.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!