aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes file renameTo() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "file renameTo() method" Watch "file renameTo() method" New topic
Author

file renameTo() method

Joshua Fix
Ranch Hand

Joined: Sep 18, 2007
Posts: 57
I am trying to use the an example from the KS/BB book to test renaming files with the following code:

And I get the output:
old.txt
new.txt

I would expect both file1 and file2 to now have the name "new.txt". What am I missing?


SCJP 5.0
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

renameTo returns a boolean to tell you if it succeeded or not. Did you try to check the return value ? It's always a good idea to take the value returned to see if something has failed.


[ December 04, 2007: Message edited by: Christophe Verre ]

[My Blog]
All roads lead to JavaRanch
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

Actually when you call file1.getName(), it won't return the new file name even after you've renamed it.


SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
No, even when the renaming works, it does not affect the File objects; it just affects the physical file.

Before the renaming, file1 refers to a file that exists, and file2 refers to a file that does not exist. (Presumably.)

After the renaming (assuming it worked), file1 refers to a file that does not exist (under that name), and file2 refers to a file that does exist.


"I'm not back." - Bill Harding, Twister
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

Oops, that's right. The blurb on checking the return value still stands, but even if it were true, that would not change the name hold by the File instance. I'll copy it 100 times.
nico dotti
Ranch Hand

Joined: Oct 09, 2007
Posts: 124
Funny, I was just working on that same section of the book tonight. You should use the dir.list() method (dir is actually an object of type File in this case) and stuff that into a String array and loop through (off the top of my head I believe it would be like this (dir is a File object pointing to a valid directory that exists):

String [] dirContents = dir.list();
for(String s : dirContents)
System.out.println( s );// prints each file out so you can see if renameTo
// worked or not.
You could do that before and after and you should see whether your rename worked or not. Of course renameTo(File) returns a boolean so you could check that way too, it's just nice too see the file contents if you're like me
[ December 05, 2007: Message edited by: nico dotti ]
Vidhya Ramaswamy
Ranch Hand

Joined: Oct 10, 2007
Posts: 65
That is really strange. Joshua, I tried your sample code, but only by using the createNewFile() for file1(for physically creating it).


Output:
true
false
old.txt

After running this code, I checked in the directory structure, but there is only one file: new.txt( I did not use createNewFile() on file2). So, it is actually renaming the file, but for some reason, not reflecting it in the getName(). But why then is renameTo() returning false ???
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
File objects are immutable. Remember, a File object is only meant to represent a file name, not the underlying filesystem entry (at least, not directly). Among other things, this means that a File object may correspond to a non-existent file, or even a syntactically invalid path.

I recommend that you basically treat File as a special type of String that you can use for filesystem operations. This may make it more intuitive to think about behaviors like the renameTo() behavior described here, since Strings are also immutable.
[ December 05, 2007: Message edited by: Kelvin Lim ]

SCJP 5.0
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Kelvin]: File objects are immutable.

Well, that's arguable. The path info is immutable, and that's the primary point to be made here, true. But the File object does also have methods that give info on the physical file, like exists(), isDirectory(), lastModified(), etc, and it has mehtods that can alter the physical file, like delete(), createNewFile(), mkdir(), etc. Thus, a File object can behave like a mutable object. Whether it is or not is a matter of semantics, I suppose. I don't think the class fits comfortable in either category unless we use a mroe precise definition of what we mean by immutable.
Vidhya Ramaswamy
Ranch Hand

Joined: Oct 10, 2007
Posts: 65
Try to use FileWriter to create the file, and then most importantly, close the file before renaming it. The renameTo() returns true in this case. A FileWriter(at the least) is required to create the file since File class itself does not have a close().
But, as Kelvin pointed out, the File object's filename is immutable, only the underlying physical file is renamed. The code I used is as follows:

Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Originally posted by Jim Yingst:
[Kelvin]: File objects are immutable.

Well, that's arguable.


Hi Jim,

I understand your point, but Sun's API docs also explicitly describe File objects as "immutable". This suggests that the designers of the class also saw its instances as basically representing just the pathname string, rather than the corresponding filesystem entry. From this perspective, the delete(), createNewFile(), etc methods are merely utility functions that apply the pathname string as input to filesystem operations, rather than mutators of the File object itself. This would explain the rationale behind renameTo() not updating the File object, which is what I'm trying to help elucidate here.
Meher Parveen
Greenhorn

Joined: Nov 25, 2007
Posts: 25
Hi everyone,

Here is something interesting i have noticed pertaining to renameTo() method:
File dir1 = new File("dir1");
dir1.mkdir();
File dir2 = new File("dir2");
dir1.renameTo(dir2);
File f1= new File(dir1, "file1"); //Line 1
File f2 = new File(dir2, "file2"); //Line 2

Line 1 fails at runtime, giving an error of "cannot find path specification" where as Line 2 runs successfully!

I am guessing this has something to do with File being immutable object.
But i don't understand what is happening above here, since mkdir is not invoked on dir2, but still it represents a valid directory?

Regards,
Meher
Meher Parveen
Greenhorn

Joined: Nov 25, 2007
Posts: 25
Correction to previous post:
the code should be :
File dir1 = new File("dir1");
dir1.mkdir();
File dir2 = new File("dir2");
dir1.renameTo(dir2);
File f1= new File(dir1, "file1");
f1.createNewFile();//Line 1
File f2 = new File(dir2, "file2");
f2.createNewFile();//Line 2

Thnaks,
Meher
Sid Robin
Ranch Hand

Joined: Nov 24, 2007
Posts: 53
dir1.renameTo(dir2);

after the execution of this line ,the directory is renamed to dir2 from dir1 .There is no dir1 directory (physically ) which we now have it as dir2 . henceforth the error in line1 .Am i right ?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Yes.
Pankaj Upadhyay
Greenhorn

Joined: Nov 06, 2008
Posts: 21
I will say just don't go by the name and think its for renaming. It is simply a 'move' command which helps in moving a file from a source path to a target path. So if this command executes successfully, file/directory will be moved to target path and file will not exist in the source path. The main thing which we should note here is that this action is platform dependent.

Sun API says..

Whether or not this method can move a file from one filesystem to another is platform-dependent. The return value should always be checked to make sure that the rename operation was successful.



Pankaj Upadhyay (SCJP 1.6 == 86%)
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13875
    
  10

Pankaj, please note that you are replying to a topic from December 2007.

I don't think the person who posted the question is still waiting for an answer. (Please don't wake the zombies).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Samrat Som
Ranch Hand

Joined: Feb 04, 2009
Posts: 40
Hey Jasper

He was always like that . The dude is one of my college buddy, and he used to wake up late in every aspect of it. But wakes up with a bang ....


SCJP 1.6
SCWCD 1.5 (Preparing...)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: file renameTo() method
 
Similar Threads
Running Batch Files
renameTo() and delete() not working
I/O Question.
renameTo()
renaming image