Skip to main content

How to copy a file in Kotlin

How to copy a file in Kotlin.

Here's a detailed step-by-step tutorial on how to copy a file in Kotlin:

  1. Import the necessary classes and methods:

    import java.io.File
    import java.io.FileInputStream
    import java.io.FileOutputStream
    import java.io.IOException
  2. Create a function to copy the file:

    fun copyFile(sourceFile: File, destinationFile: File) {
    try {
    // Create input and output streams
    val inputStream = FileInputStream(sourceFile)
    val outputStream = FileOutputStream(destinationFile)

    // Buffer to read data from the source file
    val buffer = ByteArray(1024)
    var length: Int

    // Read from the source file and write to the destination file
    while (inputStream.read(buffer).also { length = it } > 0) {
    outputStream.write(buffer, 0, length)
    }

    // Close the streams
    inputStream.close()
    outputStream.close()

    println("File copied successfully.")
    } catch (e: IOException) {
    println("An error occurred while copying the file.")
    e.printStackTrace()
    }
    }
  3. Create instances of the source and destination files:

    val sourceFile = File("path/to/source/file.txt")
    val destinationFile = File("path/to/destination/file.txt")

    Replace "path/to/source/file.txt" with the actual path to your source file, and "path/to/destination/file.txt" with the desired path for the copied file.

  4. Call the copyFile function and pass in the source and destination files:

    copyFile(sourceFile, destinationFile)

    This will copy the contents of the source file to the destination file.

That's it! You have successfully copied a file using Kotlin. You can modify the code as per your requirements, such as handling different file types or specifying different file paths.