| Author |
immutability of java.io.File
|
Yuriy Zilbergleyt
Ranch Hand
Joined: Dec 13, 2004
Posts: 429
|
|
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
Joined: Oct 29, 2001
Posts: 8264
|
|
|
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.
|
"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
|
 |
Yuriy Zilbergleyt
Ranch Hand
Joined: Dec 13, 2004
Posts: 429
|
|
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
Joined: Jan 30, 2000
Posts: 18670
|
|
[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.
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: immutability of java.io.File
|
|
|