-1

I am using the following code but I am not able to rename the file.There is no such file newname.txt in the system as well. I am using JRE6. Please help me out! Also I have tried to rename using Files class, That too isn't working.

File f1 = new File("oldname.txt");
File f2 = new File("newname.txt");
boolean b = f1.renameTo(f2);

The same code gets execute on SunOs UNIX but not on my windows 7. Why is it so ? Can I do something to execute it on my local machine?

Yati Sawhney
  • 1,372
  • 1
  • 12
  • 19

2 Answers2

0

File path to oldname.txt is not correct, Try giving the absolute path and check it works like "c:\oldname.txt"

File f1 = new File("c:\\oldname.txt"); File f2 = new File("c:\\newname.txt"); boolean b = f1.renameTo(f2);

at the end print the value of b

amith
  • 399
  • 1
  • 2
  • 11
0

Ref: Rename a file using Java (edited little bit to fit your requirment)

File f1 = new File("oldname.txt");
File f2 = new File("newname.txt");

if (!f1.exists())
       throw new java.io.FileNotFoundException("file not found");   
if (f2.exists())
   throw new java.io.IOException("file exists");

// Rename file (or directory)
boolean success = f1.renameTo(f2);

if (!success) {
   // File was not successfully renamed
}
Community
  • 1
  • 1
muzahidbechara
  • 253
  • 1
  • 14