Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help on File class

 
Abhaya Patel
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package assignment;

import java.io.File;

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

Thanking

Abhay


 
santhosh varala kumar
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
file
2. Then apply the operation.

 
isha krishnan
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Samuel March
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
compare your code...
f1.renameTo(f1=new File("C:/test1.txt"));
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic