Sling Academy
Home/Kotlin/Moving Files to a New Directory in Kotlin

Moving Files to a New Directory in Kotlin

Last updated: November 30, 2024

When working with file operations in Kotlin, moving files from one directory to another is a common task that can be done efficiently using Kotlin's standard library. This article will guide you through the process of moving files to a new directory with multiple code examples that demonstrate basic and more advanced file moving operations.

Basic File Moving in Kotlin

To move a file in Kotlin, you can use the Files class from the Java NIO libraries, which are easily accessible in Kotlin.


import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption

fun moveFile(sourcePathStr: String, destPathStr: String) {
    val sourcePath: Path = Paths.get(sourcePathStr)
    val destPath: Path = Paths.get(destPathStr)
    
    Files.move(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING)
    println("File moved from " + sourcePath.toString() + " to " + destPath.toString())
}

fun main() {
    val source = "/path/to/source/file.txt"
    val destination = "/path/to/destination/file.txt"
    
    moveFile(source, destination)
}

In the code above, the move() method from the Files class is used, which takes three arguments: the source path, the destination path, and an option that determines how the move should be handled, such as replacing an existing file.

Moving a File to a New Directory and Creating Directories if Necessary

Sometimes, the target directory might not exist, and you'll need to create it before moving the file. The following code shows how to handle such a situation:


fun moveFileToDirectory(sourcePathStr: String, destDirPathStr: String) {
    val sourcePath: Path = Paths.get(sourcePathStr)
    val destDirPath: Path = Paths.get(destDirPathStr)
    
    if (!Files.exists(destDirPath)) {
        Files.createDirectories(destDirPath)
        println("Created directories for path: " + destDirPath.toString())
    }
    val destPath = destDirPath.resolve(sourcePath.fileName)
    Files.move(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING)
    println("File moved from " + sourcePath.toString() + " to " + destPath.toString())
}

fun main() {
    val source = "/path/to/source/file.txt"
    val destinationDir = "/path/to/destination/directory/"
    
    moveFileToDirectory(source, destinationDir)
}

This script first checks if the destination directory exists, and if not, it uses Files.createDirectories() to create it. Then it moves the file to this new location.

Handling Exceptions

File operations can lead to various exceptions, such as trying to move a file that doesn't exist or permissions issues. Thus, it's a good practice to handle exceptions accordingly:


fun safeMoveFile(sourcePathStr: String, destPathStr: String) {
    val sourcePath: Path = Paths.get(sourcePathStr)
    val destPath: Path = Paths.get(destPathStr)
    
    try {
        Files.move(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING)
        println("File successfully moved from " + sourcePath.toString() + " to " + destPath.toString())
    } catch (e: Exception) {
        println("Failed to move file: " + e.message)
    }
}

fun main() {
    val source = "/path/to/source/file.txt"
    val destination = "/path/to/destination/file.txt"
    
    safeMoveFile(source, destination)
}

Wrapping the call in a try-catch block helps capture errors such as IOExceptions, thus providing a way to react to errors, for example by logging them or retrying operations later.

Conclusion

You've now learned how to move files in Kotlin using Java NIO libraries, including handling exceptions and creating non-existing directories as needed. These techniques should help you in handling file operations efficiently in your Kotlin applications.

Next Article: Copying Files and Directories with Kotlin

Previous Article: Renaming Files and Directories in Kotlin

Series: Kotlin - File & OS

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin