Rename a file in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.io.File import java.io.IOException import java.nio.file.FileAlreadyExistsException import java.nio.file.NoSuchFileException fun main() { try { val src = File("source.txt") if (!src.exists()) { throw NoSuchFileException("Source file doesn't exist") } val dest = File("destination.txt") if (dest.exists()) { throw FileAlreadyExistsException("Destination file already exist") } val success = src.renameTo(dest) if (success) { println("Renaming succeeded") } } catch (e: IOException) { e.printStackTrace() } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.io.IOException import java.nio.file.Files import java.nio.file.Paths fun main() { val src = Paths.get("source.txt") val dest = Paths.get("destination.txt") try { Files.move(src, dest) println("Renaming succeeded") } catch (e: IOException) { e.printStackTrace() } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.IOException import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption fun main() { val src = Paths.get("source.txt") val dest = Paths.get("destination.txt") try { Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING) println("Renaming succeeded") } catch (e: IOException) { e.printStackTrace() } } |
That’s all about renaming a file in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)