How to Rename file in Java

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.

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”.

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