Rename File in Java – File.renameTo()

Problem Statement:

How to Rename File in Java?

Java IO Package

Java IO Package


Rename file in java is very simple using Java IO API. We have to use renameTo() of File class passing the new instance of file as shown below. Note this method is inherently platform dependent. This method returns true if rename operation is successful and returns false if the rename operation fails. If the new file with the destination abstract pathname already exists or the file doesn’t exist, the renameTo() methods fails..

Always the return value should be checked to make sure the rename was successful.


public class STXRenameFile 
    public static void main(String[] args)
         File currentFile =new File("technostixs.txt");
         File newFile =new File("technostixsNew.txt");
         // Renames the file denoted by the abstract pathname provided. 
         // Behavior of this method are inherently platform-dependent
              System.out.println("STXRenameFile: technostix.txt renamed succesfully to technostixsNew.txt!!");
              System.out.println("STXRenameFile: Renaming to technostixsNew.txt failed!!");


Case 1: There should be a fail named technostixs.txt at c:\\technostixs\\java path.

STXRenameFile: technostix.txt renamed successfully to technostixsNew.txt!!

Case 2 : If the file technostixs.txt doesnot exist, the renameTo() methods fails.

STXRenameFile: Renaming to technostixsNew.txt failed!!

Java API used in the example



Refer below path to get the complete details about Java IO File class.


You may also like this



TechnoStixs is a dedicated weblog for Java/J2EE and web developers. We take pride in our work. Every publication is carefully analyzed, written and tested to ease the understanding of the topic or subject.

We cover Java Core Technologies, eCommerce, J2EE Frameworks, Web Service, Build Tools, Unit Test Frameworks and Others.

1,659 total views, 2 views today

Add comment