Java comes with renameTo() method to rename a file. However , this method is really platform-dependent: you may successfully rename a file in *nix but failed in Windows. So, the return value (true if the file rename successful, false if failed) should always be checked to make sure the file is rename successful.

File.renameTo() Example

package com.mkyong.file;
 
import java.io.File;
 
public class RenameFileExample 
{
    public static void main(String[] args)
    {	
 
		File oldfile =new File("oldfile.txt");
		File newfile =new File("newfile.txt");
 
		if(oldfile.renameTo(newfile)){
			System.out.println("Rename succesful");
		}else{
			System.out.println("Rename failed");
		}
 
    }
}

Reference

  1. File renameTo() documentation
Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website mkyong.com is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts