How to rename a file?


Levels of difficulty: / perform operation:

Problem & Solution

This example demonstrates how to renaming a file using oldName.renameTo(newName) method of File class.

JAVA Program

import java.io.File;

public class Main {
   public static void main(String[] args) {
      File oldName = new File("C:/program.txt");
      File newName = new File("C:/java.txt");
      if(oldName.renameTo(newName)) {
         System.out.println("renamed");
      } else {
         System.out.println("Error");
      }
   }
}

Output

The above code sample will produce the following result.To test this example, first create a file ‘program.txt’ in ‘C’ drive.

renamed