Rename a File in Java

Exercise:

Write a Java Program to rename a file.

Click Here to View the Solution!
import java.io.File; 
 public class Main {
   public static void main(String[] args) {
  
     // creating a file object
     File file = new File("oldName");
       
     // create a file
     try {
       file.createNewFile();
     }
     catch(Exception e) {
       e.getStackTrace();
     }
  
     // create an object containing the new name of file
     File newFile = new File("newName");
  
     // change the name of file
     boolean value = file.renameTo(newFile);
  
     if(value) {
       System.out.println("The name of the file is changed.");
     }
     else {
       System.out.println("The name cannot be changed.");
     }
   }
 } 
Click Here to View the Output!
The name of the file is changed.
Click Here to View the Explanation!
  • This program deals with changing the name of a file (rename).
  • The first step of execuion instantiates a File object named file.
  • The argument oldName specifies existing name for the file object.
  • Then a new file is created by employing createNewFile() method by file instance.
  • Again a new object newFile of ‘File’ is instantiated, this time with newName in the argument.
  • Next statement makes an attempt to change the name of ‘file’ by calling renameTo() method upon it.
  • Results are stored in value variable.
  • If ‘value’ holds ‘true’, then ‘The name of the file is changed.’ is displayed on the console.
  • If ‘value’ holds ‘false’, then ‘The name cannot be changed.’ is printed by the system.

%d bloggers like this: