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 is used of File class.

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 create object of File class and and replace file path with path of directory.

Now create another object of File class and replace file path with renaming path directory. In the next step using renameTo() method rename abstract pathname of a file to given pathname.

Then using if else check if rename operation is successful. If it returns true then rename operation is successful. If it returns false then rename operation is not successful. 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.java");
      File renameFile = new File("D:/Project/flowerbrackets.java");
      boolean rename = oldFile.renameTo(renameFile);
      if(rename == true)
      {
         System.out.println("Rename successful");
      }
      else
      {
         System.out.println("Rename failed");
      }
   }
}


Output:

Rename successful


move() method

java.nio.file.Files class defines move method to move or rename a file in a platform independent manner.

This operation is done using resolveSibling() method which converts a given path string to a Path and resolves it against this path’s parent path.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class RenameMoveFile 
{
   public static void main(String[] args) throws IOException
   {
      Path oldFile = Paths.get("D:/Project/flower.java");
      try
      {
         Files.move(oldFile, oldFile.resolveSibling("flowerbrackets.java"));
         System.out.println("Rename successful");
      }
      catch(IOException ex)
      {
         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.