Sling Academy
Home/Kotlin/Working with Binary Files in Kotlin

Working with Binary Files in Kotlin

Last updated: November 30, 2024

In this article, we will cover how to work with binary files in Kotlin. Binary files store data in a format that is not meant for direct interpretation by the human eye. However, they can be efficient for storing readable and non-readable data such as images, video, and compiled software applications. We will delve into reading from and writing to binary files using Kotlin's built-in libraries.

Reading Binary Files

To read from a binary file in Kotlin, you can use the FileInputStream class, which provides operations to read bytes from the file. This is best suited for scenarios where you need to handle files that are predominantly byte-oriented.


import java.io.FileInputStream
import java.io.IOException

fun readBinaryFile(filePath: String) {
    try {
        val inputStream = FileInputStream(filePath)
        var byte: Int

        // Reading bytes from file
        while (inputStream.read().also { byte = it } != -1) {
            print(byte.toChar()) // Display byte as char
        }

        inputStream.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

In this code snippet, we read each byte from the file located at filePath until we reach the end of the file, which is indicated by the method read() returning -1.

Writing to Binary Files

To write data to a binary file, you can use FileOutputStream, which enables writing byte data to files efficiently.


import java.io.FileOutputStream
import java.io.IOException

fun writeBinaryFile(filePath: String, content: ByteArray) {
    try {
        val outputStream = FileOutputStream(filePath)

        // Writing bytes to file
        outputStream.write(content)

        outputStream.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

The function writeBinaryFile takes a file path and a byte array. The byte array represents the data that will be written to the file. With FileOutputStream, it's straightforward to push this data onto the disk, storing it in binary form.

Copying Binary Files

Copying a binary file involves reading the bytes from the source file and writing them to the destination file. You can implement this by combining both reading and writing operations.


fun copyBinaryFile(sourcePath: String, destPath: String) {
    try {
        val inputStream = FileInputStream(sourcePath)
        val outputStream = FileOutputStream(destPath)

        var byte: Int

        // Copy process
        while (inputStream.read().also { byte = it } != -1) {
            outputStream.write(byte)
        }

        inputStream.close()
        outputStream.close()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

This function first establishes input and output streams for the source and destination paths respectively. It then reads and writes each byte from the source file to the destination file, achieving the copy operation.

Conclusion

Working with binary files in Kotlin is straightforward thanks to its robust file I/O capabilities. By understanding how to read from and write to these files, you can efficiently manage and manipulate binary data, whether it be for storing images, save states, or executable data. Always ensure that you handle any potential IOException to maintain stable applications.

Next Article: Using Kotlin’s `BufferedReader` for Efficient File Reading

Previous Article: Appending Data to Existing Files 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