aspose file tools
The moose likes Java in General and the fly likes immutability of java.io.File Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "immutability of java.io.File" Watch "immutability of java.io.File" New topic
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
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: immutability of java.io.File
 
Similar Threads
accessing .newsrc files...
Setting a filename filter in Filedialog
How to know the path of the application being executed
File renameto doesn't change the name of the file
java.io.File exception