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

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

    val decodedFile = new File(filename + ".decoded")
    val decoded = new BASE64Decoder().decodeBuffer(encoded)
    val decodedStream = new FileOutputStream(decodedFile)

Leave a Reply

Your email address will not be published. Required fields are marked *