How to Rename a File in Java
Java provides a built-in class java.io.File for standard file operations. This can be used for renaming files as well. The following example shows how a file can be renamed in Java.
import java.io.File; /** * How to rename a file in Java 7 and below. * @author jj */ public class RenameFile1 { public static void main(String[] args) { // Please ensure that the following file/folder exists File f = new File("c:/temp/test1.txt"); // The following file should not exist while running the program File rF = new File("c:/temp/test2.txt"); if(f.renameTo(rF)) { System.out.println("File was successfully renamed"); } else { System.out.println("Error: Unable to rename file"); } } }
Since Java 8, a new class java.nio.file.Files was introduced. This is a more reliable and flexible option than the java.io.File. The following example shows the recommended way of renaming files in Java 8.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; /** * How to rename a file in Java 8 and above. * @author jj */ public class RenameFile2 { public static void main(String[] args) { Path f = Paths.get("c:/temp/test1.txt"); Path rF = Paths.get("c:/temp/test2.txt"); try { Files.move(f, rF, StandardCopyOption.REPLACE_EXISTING); System.out.println("File was successfully renamed"); } catch (IOException e) { e.printStackTrace(); System.out.println("Error: Unable to rename file"); } } }