Kotlin Program to Convert File to Byte Array and Vice-Versa

Kotlin Program to Convert File to byte array and Vice-Versa. Before we convert a file to byte array and vice-versa, we assume we have a file named test.txt in our src folder. In the below program, we store the path to the file in the variable path.

Kotlin Program to Convert File to Byte Array and Vice-Versa

Source Code

import java.io.IOException
import java.nio.file.Files
import java.nio.file.Paths
import java.util.Arrays

fun main(args: Array<String>) {

    val path = System.getProperty("user.dir") + "\\src\\test.txt"

    try {
        val encoded = Files.readAllBytes(Paths.get(path))
        println(Arrays.toString(encoded))
    } catch (e: IOException) {

    }
}

Output