2

同種の型付きオブジェクトのストリームが与えられた場合、それらをバイナリにシリアル化し、ディスクに書き込み、ディスクから読み取り、Scala Pickling を使用して逆シリアル化するにはどうすればよいでしょうか?

例えば:

object PicklingIteratorExample extends App {

    import scala.pickling.Defaults._
    import scala.pickling.binary._
    import scala.pickling.static._

    case class Person(name: String, age: Int)

    val personsIt = Iterator.from(0).take(10).map(i => Person(i.toString, i))
    val pklsIt = personsIt.map(_.pickle)

    ??? // Write to disk
    val readIt: Iterator[Person] = ??? // Read from disk and unpickle
} 
4

1 に答える 1

1

標準ファイルの場合は、次の方法を見つけます。

object PickleIOExample extends App {
    import scala.pickling.Defaults._
    import scala.pickling.binary._
    import scala.pickling.static._

    val tempPath = File.createTempFile("pickling", ".gz").getAbsolutePath
    val outputStream = new FileOutputStream(tempPath) 
    val inputStream = new FileInputStream(tempPath) 

    val persons = for{
        i <- 1 to 100
    } yield Person(i.toString, i)

    val output = new StreamOutput(outputStream)
    persons.foreach(_.pickleTo(output))
    outputStream.close()

    val personsIt = new Iterator[Person]{
        val streamPickle = BinaryPickle(inputStream)

        override def hasNext: Boolean = inputStream.available > 0

        override def next(): Person = streamPickle.unpickle[Person]
    }

    println(personsIt.mkString(", "))
    inputStream.close()
}

しかし、gzip 圧縮されたファイルで機能するソリューションをまだ見つけることができません。EOFを検出する方法がわからないので?GZIPInputStream の使用可能なメソッドが EOF を示していないため、次のコードは EOFexception をスローします。

object PickleIOExample extends App {
    import scala.pickling.Defaults._
    import scala.pickling.binary._
    import scala.pickling.static._

    val tempPath = File.createTempFile("pickling", ".gz").getAbsolutePath
    val outputStream = new GZIPOutputStream(new FileOutputStream(tempPath))
    val inputStream = new GZIPInputStream(new FileInputStream(tempPath))

    val persons = for{
        i <- 1 to 100
    } yield Person(i.toString, i)

    val output = new StreamOutput(outputStream)
    persons.foreach(_.pickleTo(output))
    outputStream.close()

    val personsIt = new Iterator[Person]{
        val streamPickle = BinaryPickle(inputStream)

        override def hasNext: Boolean = inputStream.available > 0

        override def next(): Person = streamPickle.unpickle[Person]
    }

    println(personsIt.mkString(", "))
    inputStream.close()
}
于 2015-06-09T13:39:55.803 に答える