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.
You should always check if rename operation is successful or not because it does not throw any exception
Java Program:
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("-----------------");
}
}
When I ran above program, I got following output:
----------------- Rename operation is successful -----------------