Skip to content

Instantly share code, notes, and snippets.

@sc6l6d3v
Created November 1, 2016 22:33
Show Gist options
  • Save sc6l6d3v/651c52b4161aee8742fc2e250c8729a3 to your computer and use it in GitHub Desktop.
Save sc6l6d3v/651c52b4161aee8742fc2e250c8729a3 to your computer and use it in GitHub Desktop.
/**
* Created by hkatz on 11/1/16.
*/
import scala.pickling._
import scala.pickling.binary.{ BinaryPickle => bipck}
import scala.pickling.fastbinary.{ BinaryPickle => fbipck}
//import scala.pickling.json._
import scala.pickling.binary._
import java.io._
class Brotherhood(
var name: String,
var brothers: Option[Seq[Brotherhood]])
object Brotherhood {
def pickleTo(brothers: Brotherhood, filename: String) = {
// convert to Pickle binary object
val brothersPickle = brothers.pickle
// get the pickle bytes array
val brothersPickleByteArray = brothersPickle.value
// write bytes array into the file
val fos = new FileOutputStream("./" + filename)
fos.write(brothersPickleByteArray)
fos.close
}
def unpickleFrom(filename: String): Brotherhood = {
val brothersRawFromFile = scala.io.Source.fromFile("./" + filename).map(_.toByte).toArray
val brothersUnpickleValue = bipck(brothersRawFromFile)
val brothersUnpickle: Brotherhood = brothersUnpickleValue.unpickle[Brotherhood]
brothersUnpickle
}
}
object SerializationDemo extends App {
val tom = new Brotherhood("Tom", None)
val smith = new Brotherhood("Smith", None)
val richard = new Brotherhood("Richard", None)
val brothers = new Brotherhood("Assassin", Option(Seq(tom, smith, richard)))
Brotherhood.pickleTo(brothers, "PickleBinaryFile")
val brotherhoodUnpickle = Brotherhood.unpickleFrom("PickleBinaryFile")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment