English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java program to rename a file

Comprehensive Java Examples

In this tutorial, we will learn how to rename a file using Java.

InJava fileThe class provides the renameTo() method to change the file name. If the renaming operation is successful, it returns true; otherwise, it returns false.

Example: Rename a file using Java

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 containing the new file name
    File newFile = new File("newName");
    //Change the file name
    boolean value = file.renameTo(newFile);
    if(value) {
      System.out.println("The file name has been changed.");
    }
    else {
      System.out.println("The name cannot be changed.");
    }
  }
}

In the above example, we created a file object named file. This object stores information about the specified file path.

File file = new File("oldName");

Then, we create a new file using the specified file path.

//Create a new file with the specified path
file.createNewFile();

Here, we created another file object named newFile. This object stores information about the specified file path.

File newFile = new File("newFile");

To change the file name, we used the renameTo() method. The name specified by the newFile object is used to rename the file specified by the file object.

file.renameTo(newFile);

If the operation is successfulThe following message will be displayed.

The file name has been changed.

If the operation cannot be successfulThe following message will be displayed.

The name cannot be changed.

Comprehensive Java Examples