Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

file renameTo() method

 
Joshua Fix
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually when you call file1.getName(), it won't return the new file name even after you've renamed it.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.
 
Pankaj Upadhyay
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15439
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Samrat Som
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic