This post will discuss how to rename a file in Kotlin.

1. Using File#renameTo() function

A simple solution is to use the File#renameTo() function for renaming a file, which returns a boolean value indicating whether the renaming was successful or not. Note that the function’s behavior is platform-dependent, and it doesn’t throw a java.io.IOException on I/O failure.

 
The following solution demonstrates the usage of the File#renameTo() function. Note that if the file is renamed successfully, a success message is displayed. If the source file doesn’t exist, java.nio.file.NoSuchFileException is thrown. If the destination path already exist, java.nio.file.FileAlreadyExistsException is thrown.

Download Code

2. Using Files.move() function

Alternately, we can use the Files.move() function to rename (or move) a file that throws a java.io.IOException if an I/O error occurs. The usage is demonstrated below:

Download Code

 
If the target file already exists, the Files.move() function throws java.nio.file.FileAlreadyExistsException. To replace the target file, we can specify the REPLACE_EXISTING option.

Download Code

That’s all about renaming a file in Kotlin.