File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes Need help on File class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Need help on File class" Watch "Need help on File class" New topic

Need help on File class

Abhaya Patel

Joined: Feb 27, 2008
Posts: 2
package assignment;


public static void main(String arg[]){

File f1=new File("C:/test.txt");

System.out.println("File name :"+ f1.getName());

f1.renameTo(new File("C:/test1.txt"));

System.out.println(("File name :"+ f1.getName());


hello guys,

In the above code all are working fine. I just created a file "test.txt" and the rename the file by using the "renameTo()" method.
I printed the name of the file by invoking the "getNme()" method. The renameTo() method rename the file "test.txt" to "test1.txt"
but the program prints same for both the print method :

File name :test.txt //before renaming
File name :test.txt //after renaming

So the question is that why the second one "test.txt" why not "test1.txt" while the file "test.txt" is renamed to "test1.txt"

Waiting for reply



santhosh varala kumar

Joined: Nov 05, 2009
Posts: 25
This operations will work if the file test.txt is already created. Since both are not phyiscally created. Only virtually file path are calculated. Hence File rename operation is failed.

System.out.println(f1.renameTo(new File("C:/test1.txt"))); will always returns false.

Due to this you are getting same value.

1.Todo this first create a file using FileWriter/FileOutputStream . or an existing created
2. Then apply the operation.

isha krishnan
Ranch Hand

Joined: Nov 10, 2008
Posts: 50
hi Santosh,
I tried what you have told but i have one doubt.
when i write this line,

System.out.println(f1.renameTo(new File("C:/test1.txt"));

it displays test.txt only though that file has already been renamed.Why is it that f1 value is not replaced?
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
renameTo will return true only if the name given in the file object doesnot already exist inthe path else it will not rename the file and hence it reutrn false.

Also if the file name is not valid it iwll return false.


Failure is not an option.
Samuel March
Ranch Hand

Joined: Oct 28, 2009
Posts: 39
compare your code...
f1.renameTo(f1=new File("C:/test1.txt"));

...did you have the fish?!............................ No.
I agree. Here's the link:
subject: Need help on File class
It's not a secret anymore!