In this post we will see an example on how we can rename file in java.
We will use the File.renameTo(File dest) method.
File.renameTo(File dest) renames the current file with the name of the file in the param.
In other words renameTo will move the original file to whatever location is specified in the destination param.
renameTo() returns “true” if file is renamed/moved successfully.
In other case it will return “false”
Example : Rename File in java in same directory
In this example we see that both the originalFile and newFile are from the same directory. Hence renameTo will only rename the originalFile to new File name.
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 |
package com.kscodes.sampleproject; import java.io.File; import java.io.IOException; public class FileHandling { /** * @param args */ public static void main(String[] args) throws IOException { renameFile(); } public static void renameFile() throws IOException { File originalfile = new File("C:\\kscodes\\originalfile.txt"); File newFile = new File("C:\\kscodes\\newFile.txt"); boolean fileRenamed = originalfile.renameTo(newFile); if (fileRenamed) { System.out.println("File Renamed successfully"); } else { System.out.println("File couldnt be Renamed"); } } } |
Example : Rename File in java in different directory
In this example you will see that the destination directory is different. Here renameTo() will move the original file from “C:\\kscodes” to “C:\\kscodes\\work” directory and then rename it to “newFile.txt”.
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 |
package com.kscodes.sampleproject; import java.io.File; import java.io.IOException; public class FileHandling { /** * @param args */ public static void main(String[] args) throws IOException { renameFile(); } public static void renameFile() throws IOException { File originalfile = new File("C:\\kscodes\\originalfile.txt"); File newFile = new File("C:\\kscodes\\work\\newFile.txt"); boolean fileRenamed = originalfile.renameTo(newFile); if (fileRenamed) { System.out.println("File Renamed successfully"); } else { System.out.println("File couldnt be Renamed"); } } } |
When performing any operation on File, you will need to handle the IOException exception.
You can get more details on the File API and the renameTo here