0

I want to rename a file in Java. My working platform is Ubuntu. The renameFile() didn't work for me. Is there any other ways to rename a file ?

ADDED :

File file = new File( "/home/test/filename.txt" );

if ( file.renameTo( new File( "/home/test/modified.txt" ) ) ) {
    System.out.println( "Rename succesful" );
} else {
    System.out.println( "Rename failed" );
}
Manoj Shrestha
  • 4,246
  • 5
  • 47
  • 67
  • 1
    What have you tried and what are the errors you get? Do other operations work on the file? Do you have access rights to the file? – LastFreeNickname Sep 10 '13 at 14:36

1 Answers1

3

You can use File.renameTo(newFileName)

If this doesn't work, you need to work out why as this method isn't very helpful. e.g. you can't rename a files which isn't there or you don't have permissions to the directories.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • [API of renameTo()](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo(java.io.File)) – Suresh Atta Sep 10 '13 at 14:36
  • Yeah, Sounds like it's access privilege issue. I tried renaming the file in a different location. It worked. Just wondering though, the instance variable 'file' is holding the previous file name. i.e. file.getName() is giving me the old name "filename.txt". – Manoj Shrestha Sep 10 '13 at 14:46
  • @ManojShrestha The File object is immutable so it doesn't change. It is just a reference to a path which may or may not exist. – Peter Lawrey Sep 10 '13 at 14:49