How to rename file in Java

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;
public class RenameFileExample 
    public static void main(String[] args)
		File oldfile =new File("oldfile.txt");
		File newfile =new File("newfile.txt");
			System.out.println("Rename succesful");
			System.out.println("Rename failed");


  1. File renameTo() documentation
Tags :

About the Author

Founder of and, 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.


  • Pingback: watch movies online free()

  • Pingback: Blue Coaster33()

  • Anand

    Hi you will get complete java code for all file operations here –

  • Sudhir

    sometimes renameTo doesn’t work in windows.
    I am still trying to find the the answer.
    Can you please help me.


  • Karren Omoto

    Someone I work with visits your site frequently and recommended it to me to read also. The writing style is great and the content is relevant. Thanks for the insight you provide the readers!