Rename a File or Directory in Java



The method File.renameTo() method of the java.io package is used to rename a file or directory. This method requires a single parameter i.e. the name that the file or directory is renamed to and it returns true on the success of the renaming or false otherwise.

Syntax

public boolean renameTo(File dest)

Steps to rename a file or directory using File renameTo() method

Below are the steps to rename a file or directory using the File renameTo() method ?

  • Import File class from java.io package
  • Define the demo class with the main method.
  • Create File objects file1 and file2.
  • Use createNewFile() to create demo1.txt and demo2.txt.
  • Attempt to rename file1 to file2 using renameTo().
  • Print if the file was renamed.
  • Catch and print any exceptions.

Java program to rename a file or directory

A program that demonstrates this is given as follows ?

import java.io.File;
public class Demo {
 public static void main(String[] args) {
try {
 File file1 = new File("demo1.txt");
 File file2 = new File("demo2.txt");
 file1.createNewFile();
 file2.createNewFile();
 boolean flag = file1.renameTo(file2);
 System.out.print("File renamed? " + flag);
} catch(Exception e) {
 e.printStackTrace();
}
 }
}

Output

File renamed? true

Note ? The output may vary on Online Compilers.

Code Explanation

This Java code creates two new files, "demo1.txt" and "demo2.txt", and then attempts to rename the first file to the second file. It uses the File class to create and manipulate the files. The createNewFile() method is called to create both files and then the renameTo() method is used to rename "demo1.txt" to "demo2.txt". The result of the rename operation is stored in a boolean variable flag and printed to the console, indicating whether the file was renamed successfully. If any exceptions occur during the process, they are caught and the stack trace is printed. The code demonstrates basic file operations in Java, including creating and renaming files.

Updated on: 2024-08-02T18:16:28+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements