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,


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");
         System.out.println("Rename successful");
         System.out.println("Rename failed");


Rename successful

Also read – random number generator in java

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