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

In java rename file 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.

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

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 – java example to print all alphabets

Also read – file last modified date java program

Related Posts