Move a File in Kotlin
This post will discuss how to move a file in Kotlin.
There are several methods to move a file to a different location in Kotlin. These are discussed below in detail:
1. Using Files.move() function
The standard solution to move a file is using the Files.move() function, which accepts the source and the destination path, and an optional parameter indicating how to perform the move. If the destination already exists, the moving fails by default, unless the REPLACE_EXISTING option is specified.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.StandardCopyOption fun moveFile(src: File, dest: File) { Files.move(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING) } fun main() { val from = File("src.txt") val to = File("dest.txt") try { moveFile(from, to) println("File moved successfully.") } catch (ex: IOException) { ex.printStackTrace() } } |
2. Using File.renameTo() function
Another alternative is to use the File#renameTo() function, which can be used to move a file within the same file system. This operation is platform-dependent, non-atomic, and no I/O exception is thrown on error. It is recommended to check its return value to ensure that the moving was successful or not.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.File import java.io.IOException private fun moveFile(src: File, dest: File): Boolean { return src.renameTo(dest) } fun main() { val from = File("src.txt") val to = File("dest.txt") try { val isSuccess = moveFile(from, to) if (isSuccess) { println("File Moved Successfully") } else { println("File Moved Failed") } } catch (ex: IOException) { ex.printStackTrace() } } |
That’s all about moving 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 :)