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.

Here's the content of test.txt

This is a
Test file.

Example 1: Convert File to byte[]

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) {

    }
}

When you run the program, the output will be:

[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]

In the above program, we store the path to the file in the variable path.

Then, inside the try block, we read all the bytes from the given pth using readAllBytes() method.

Then, we use Arrays' toString() method to print the byte array.

Since, readAllBytes() might throw an IOException, we've used the try-catch block in the program.


Example 2: Convert byte[] to File

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

fun main(args: Array<String>) {

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

    try {
        val encoded = Files.readAllBytes(Paths.get(path))
        Files.write(Paths.get(finalPath), encoded)
    } catch (e: IOException) {

    }

}

When you run the program, the contents of test.txt is copied to final.txt.

In the above program, we've used the same method as Example 1 to read all the bytes from the File stored in path. These bytes are stored in the array encoded.

We also have a finalPath where the bytes are to be written.

Then, we simply use the Files' write() method to write the encoded byte array to a File in the given finalPath.

Here's the equivalent Java code: Java program to convert File to byte[] and vice-versa.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges