Helping Information

Java Program to Rename File

Java Program to Rename File

Problem Definition: Java Program to Rename File.

In this post, we will learn how to rename file in Java using coding.

on the positive side if you don’t have latest version of Java click here.

Rename File

The Java File class provides the “renameTo()” method to change the name of the file. It returns “true” if the renaming operation succeeds otherwise returns “false”.

Example: Java Program to Rename File

import java.io.File;
class Main {
public static void main(String[] args) {
    // create a file object
  File file = new File("oldName");
    // create a file
    try {
      file.createNewFile();
    }
    catch(Exception e) {
      e.getStackTrace();
    }


    // create an object that contains 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.");
    }
  }
}

As shown above example, we have create a “file” object name file. The object holds information about the specific file path.

File file = new File("oldName");

We then create a new file with the specific file path.

// create a new file with the specific path
file.createNewFile();

On this side, we have create another file object named “newFile”. The object holds information about the specific file path.

File newFile = new File("newFile");

To change the name of the file, we have use the “renameTo()” method. The name specific by the “newFile” object is use to rename the file specifically by the file object.

file.renameTo(newFile);

If the operation success, For this reason the following message is shown.

The name of the file is change.

If the operation cannot success, the following message is shown.

The name cannot be change.

Related Post:

  1. Java Program to Copy File
  2. Java Program to List Files in a Directory
  3. Java Program to Create Directories
  4. Java Program to Find ASCII Value of a character

Leave a Reply

Your email address will not be published. Required fields are marked *