Although not typical nowadays, sometimes we need codes that rename files according to some use cases. This post shows how to rename a file in Java using the File and Files classes.
Other Libraries can Rename Files
There are many third-party libraries available out there that we can use. These libraries may already provide the feature as part of their capabilities. Take, for example, the Apache Camel library or Spring Integration. Suppose we are already using them; we could tap on their file-renaming capability.
Use The File renameTo Method
To make Java rename a file, we could use the renameTo method from the File class. Consider the following example.
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 | package com.turreta.file.rename; import java.io.File; public class RenameMyFile { public static boolean renameFile(String src, String dest) { File currentFileName = new File(src); File newFileName = new File(dest); return currentFileName.renameTo(newFileName); } public static void main(String[] args) { if (renameFile("C:/password.txt", "C:/backup-password.txt")) { System.out.println("Successfully renamed file"); } else { System.out.println("Unable to rename file"); } } } |
The renameTo method accepts another File object, but its internal workings are platform-dependent.
Use The Files move Method
Alternatively, we could use the move method, which is also from the java.nio.file.Files class. Consider the following Java codes that rename a file in the same directory.
1 2 3 4 5 6 7 8 9 10 11 | ... Path origName = Paths.get("/home/user1/test/MyText01.txt"); try { Files.move(origName , origName.resolveSibling("MyText02.txt")); } catch (IOException e) { // ... } ... |
Note that we are using a different class this time to rename a file. Moreover, we are passing Path objects to the move method instead of File objects. Unlike the renameTo method, the move method returns an exception when Java fails to move or rename the file.
This post is (now) part of a reboot Java tutorial.