Gary Sieling

Base64 Encoding and Decoding Example in Scala

This fairly simple example makes use of the core Java APIs to read files, demonstrating how to construct a base-64 encoded version, and then generating the original file again.

package com.garysieling {
  import java.io.{File, FileInputStream, FileOutputStream}
  import sun.misc.{BASE64Encoder, BASE64Decoder}

  object Base64 extends App {
    val filename = """C:\IdeaProjects\base64\tests.pdf"""
    Console.println("Testing " + filename)

    val file = new File(filename)
    val in = new FileInputStream(file)
    val bytes = new Array[Byte](file.length.toInt)
    in.read(bytes)
    in.close()

    val encodedFile = new File(filename + ".base64")
    val encoded = 
       new BASE64Encoder()
         .encode(bytes)
         .replace("\n", "")
         .replace("\r", "")
    val encodedStream = new FileOutputStream(encodedFile)
    encodedStream.write(encoded.getBytes)
    encodedStream.close()

    val decodedFile = new File(filename + ".decoded")
    val decoded = new BASE64Decoder().decodeBuffer(encoded)
    val decodedStream = new FileOutputStream(decodedFile)
    decodedStream.write(decoded)
    decodedStream.close()
  }
}
Exit mobile version