Java Examples - Rename a File

Advertisements


Problem Description:

How to rename a file?

Solution:

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

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");
      }
   }
}

Result:

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

renamed


Advertisements
Advertisements