In this post, we will see how to rename a file in java. We can use java.io.File ‘s rename(File dest) method to rename a file. rename method returns true if operation is success else returns false. It can use this method to move a file also.
When I ran above program, I got following output:
You should always check if rename operation is successful or not because it does not throw any exception
Java Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package org.arpit.java2blog; import java.io.File; public class RenameFileMain { /* * @Author : Aprit Mandliya */ public static void main(String[] args) { System.out.println("-----------------"); // Read the file File configFile=new File("/Users/Arpit/Desktop/config.properties"); // destination file object File configFileNew=new File("/Users/Arpit/Desktop/config_new.properties"); boolean remameSuccess=configFile.renameTo(configFileNew); if(remameSuccess) { System.out.println("Rename operation is successful"); } else { System.out.println("Rename operation is unsuccessful"); } System.out.println("-----------------"); } } |
1 2 3 4 5 |
----------------- Rename operation is successful ----------------- |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.