Sling Academy
Home/Kotlin/Copying Files and Directories with Kotlin

Copying Files and Directories with Kotlin

Last updated: November 30, 2024

Kotlin, a modern and expressive programming language, offers several ways to copy files and directories, utilizing its well-defined standard libraries. In this article, we will go over some methods to perform these operations with examples that make the task straightforward. Let's dive in!

Copying Files

To copy files, you can use the java.nio.file.Files class, which provides copy methods. Below is an example of how to copy a file from one location to another using Kotlin:

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

fun copyFile(sourcePath: String, targetPath: String) {
    val source = Paths.get(sourcePath)
    val target = Paths.get(targetPath)
    Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING)
}

fun main() {
    val sourcePath = "path/to/source/file.txt"
    val targetPath = "path/to/destination/file.txt"
    copyFile(sourcePath, targetPath)
    println("File copied successfully.")
}

In this example, the Files.copy function is employed along with StandardCopyOption.REPLACE_EXISTING to ensure that any existing file at the target location is replaced by the source file.

Copying Directories

Copying directories can be more complex as it involves copying the directory tree. For this, you can use recursion along with file walk utilities provided by Kotlin. Here’s a simple way to achieve this:

import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.SimpleFileVisitor
import java.nio.file.StandardCopyOption
import java.nio.file.attribute.BasicFileAttributes

fun copyDirectory(sourceDirPath: String, targetDirPath: String) {
    val sourceDir = Paths.get(sourceDirPath)
    val targetDir = Paths.get(targetDirPath)
    Files.walkFileTree(sourceDir, object : SimpleFileVisitor<Path>() {
        override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
            Files.copy(file, targetDir.resolve(sourceDir.relativize(file)), StandardCopyOption.REPLACE_EXISTING)
            return FileVisitResult.CONTINUE
        }

        override fun preVisitDirectory(dir: Path, attrs: BasicFileAttributes): FileVisitResult {
            Files.createDirectories(targetDir.resolve(sourceDir.relativize(dir)))
            return FileVisitResult.CONTINUE
        }
    })
}

fun main() {
    val sourceDir = "path/to/source/directory"
    val targetDir = "path/to/destination/directory"
    copyDirectory(sourceDir, targetDir)
    println("Directory copied successfully.")
}

This example uses a file visitor to traverse the directory, copying each file and creating directories as needed in the destination path.

Conclusion

Copying files and directories in Kotlin can be efficiently handled using the Java NIO API. With the examples provided, you should be able to adapt and expand on these methods to suit your specific requirements. Experiment with these code snippets to integrate file operations into your applications effectively.

Next Article: Using Kotlin to List Files in a Directory

Previous Article: Moving Files to a New Directory 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