scala 序列化(反序列化)、File操作使用示例

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013063153/article/details/53501929
package com.sparktest

import java.io._

import scala.io.Source

/**
  *
  */
@SerialVersionUID(99L) class TestSpark(val name: String) extends Serializable

object FileTest extends App {

  val teSpark = new TestSpark("Spark")

  /** Serialize an object using Java serizlization */
//  def serialize[T](o: T): Array[Byte] = {
//    val bos = new ByteArrayOutputStream() //内存输出流,和磁盘输出流从操作的层面上讲是一样的
//    val oos = new ObjectOutputStream(bos)
//    oos.writeObject(o)
//    oos.close()
//    bos.toByteArray
//  }

  def serialize[T](o: T) {
    val bos = new FileOutputStream("C:\\Users\\hello\\Desktop\\test.txt")//基于磁盘文件流的序列化
    val oos = new ObjectOutputStream(bos)
    oos.writeObject(o)
    oos.close()
  }

  serialize(teSpark)

  /** Deserialize an object using Java serizlization */
//  def deserialize[T](bytes: Array[Byte]): T = {
//    val bis = new ByteArrayInputStream(bytes)
//    val ois = new ObjectInputStream(bis)
//    ois.readObject.asInstanceOf[T]
//  }

  def deserialize[T](bytes: Array[Byte]): T = {
    val bis = new FileInputStream("C:\\Users\\Wangyao\\Desktop\\test.txt")
    val ois = new ObjectInputStream(bis)
    ois.readObject.asInstanceOf[T]
  }


  //  println(deserialize[TestCoder](serialize[TestCoder](teSpark)).name)

  println(deserialize[TestSpark](null).name)

//  for(line <- Source.fromFile("C:\\Users\\hello\\Desktop\\file.txt","GBK").getLines()) println(line)

//  println(Source.fromFile("C:\\Users\\hello\\Desktop\\file.txt","GBK").mkString)

//  for(item <- Source.fromFile("C:\\Users\\hello\\Desktop\\file.txt","GBK")) println(item)

//  println(Source.fromURL("http://spark.apache.org/","UTF-8").mkString)



}
展开阅读全文

没有更多推荐了,返回首页