Rename file or directory in Java


The method java.io.File.renameTo() 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.

A program that demonstrates this is given as follows −

Example

 Live Demo

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

The output of the above program is as follows −

Output

File renamed? true

Now let us understand the above program.

The method java.io.File.renameTo() is used to rename the file. Then the boolean value returned by the method is printed. A code snippet that demonstrates this is given as follows −

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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

269 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements