Java, Software Development

Java – Rename a file Using a File Object Example

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.

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.

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.


Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like