Java, Software Development

Java – Rename a file Using a File Object Example

java Sort Enum Properties Monitor Directory File Lambda Expression parameter return types Validate XML String XSD ExecutorService AutoCloseable Try-With-Resources Convert LocalDateTime OffsetDateTime Run Codes Before Shutdown XML Tag Lambda PostgreSQL JDBC invoke JavaScript Applet SFTP Batch hang block main thread MySQL JDBC try-with-resources delete Unencrypted SoapFault Apache CXF Remove XML Element XSLT skip execute finally public static void main constructor fields Eclipse convert Iterator Stream StreamSupport XMLEncoder XMLDecoder rename P6Spy JDBC Example PDF Version JasperReports Run from Ant iReport Page Numbers Count entities persistence context hibernate

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? Please visit our Facebook page!

You Might Also Like