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.

Download Code

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.

Download Code

That’s all about moving a file in Kotlin.