How to rename file in java

Let’s learn how to rename file in java.

How to rename file in java

To rename a file renameTo() method of File class is used.

how to rename file in java

Here’s the syntax of renameTo() method of File class.

public boolean renameTo(File dest)

renameto method returns true if and only if the renaming is succeeded; false otherwise. Many aspects of the behavior of renameTo() method are inherently platform-dependent.

Parameters:

dest the new abstract pathname for the named file.

Throws:

SecurityException – If a security manager exists and its java.lang.SecurityManager.checkWrite (java.lang.String) method denies write access to either the old or new pathnames.

NullPointerException – If parameter dest is null.

Here in the below example first we have to predefine pathname as parameter in File class. Here’s an example on how to rename file.

import java.io.*;
public class RenameFile
{
   public static void main(String[] args) throws IOException
   {
      File oldFile = new File("D:\\Project\\flower.txt");
      File newFile = new File("D:\\Project\\flowerbrackets.txt");
      if(oldFile.renameTo(newFile))
      {
         System.out.println("Rename successful");
      }
      else
      {
         System.out.println("Rename failed");
      }
   }
}


Output:

Rename successful


Also read – variables in java

So this is all about how to rename file. I hope you guys have understood the concept of renaming file in java.