Write a Kotlin Program to Convert File to byte array and Vice-Versa

Here is a Kotlin program that demonstrates how to convert a file to a byte array and vice-versa.

import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

fun fileToByteArray(file: File): ByteArray {
    val inputStream = FileInputStream(file)
    val buffer = ByteArray(file.length().toInt())
    inputStream.read(buffer)
    inputStream.close()
    return buffer
}

fun byteArrayToFile(byteArray: ByteArray, file: File) {
    val outputStream = FileOutputStream(file)
    outputStream.write(byteArray)
    outputStream.close()
}

fun main() {
    val file = File("example.txt")
    val originalText = "This is an example text."

    // Write the original text to the file
    file.writeText(originalText)

    // Convert file to byte array
    val byteArray = fileToByteArray(file)

    // Convert byte array to file
    val newFile = File("new_example.txt")
    byteArrayToFile(byteArray, newFile)

    // Read the new file to ensure it contains the original text
    val newText = newFile.readText()
    println(newText) // Output: "This is an example text."
}

In the code above, the fileToByteArray function takes a File object as input and returns a ByteArray that contains the contents of the file.

The function first creates a FileInputStream object from the file and reads the contents of the file into a byte array. Finally, the function returns the byte array.

The byteArrayToFile function takes a ByteArray and a File object as input and writes the contents of the byte array to the file.

The function first creates a FileOutputStream object from the file and writes the byte array to the output stream. Finally, the function closes the output stream.

In the main function, we create a file called “example.txt” and write the text “This is an example text.” to it.

We then convert the file to a byte array using the fileToByteArray function and convert the byte array back to a file using the byteArrayToFile function.

We then read the new file and print its contents to the console to ensure that it contains the original text.

I hope this helps!