How to rename file in java

In this post we are going to learn how to rename file in java.

how to rename file in java

To rename a file using java renameTo() method of File class is used. This method returns true if and only if the renaming succeeded; false otherwise.

Here in the below example first we are predefining pathname as parameter in File class.

// Renames the file denoted by this abstract pathname
public boolean renameTo(File dest)

Many aspects of the behavior of renameTo() method are inherently platform-dependent. Here’s the code implementation,

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 – random number generator in java

Also read – java program to check whether number is prime or not