Scala学习——字节流和文件流(对象的序列化)


package com.dtspark.scala.basics

import java.io.Serializable
import java.io.ByteArrayOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.ByteArrayInputStream
import java.io.FileOutputStream
import java.io.FileInputStream
import scala.io.Source
import scala.sys.process.ProcessBuilder.Source
import scala.sys.process.ProcessBuilder.Source

//序列化版本ID
@SerialVersionUID(1) class DTSpark(val name:String)extends Serializable

object HelloFileOpps {
  def main(args: Array[String]): Unit = {
    val dtspark= new DTSpark("Spark")
    println(new String(serialize(dtspark)))
    println(deserialize[DTSpark](serialize(dtspark)).name)
    serialize_file(dtspark)
    println(deserialize_file[DTSpark]("D:\\a.txt").name)

    //编码很重要,可能不识别
    for(line <- Source.fromFile("D:\\a.txt","GBK").getLines())println(line)
    println(Source.fromFile("D:\\a.txt","GBK").mkString)
    //for(item <- Source.fromFile("D:\\a.txt","GBK"))println(item)
    //从网络上读取
    println(Source.fromURL("https://www.baidu.com/","UTF-8").mkString)
  }
  //序列化(将对象传入,变成字节流)
  def serialize[T](o:T):Array[Byte]={
    val bos = new ByteArrayOutputStream()//内存输出流,和磁盘输出流从操作上讲是一样的
    val oos = new ObjectOutputStream(bos)
    oos.writeObject(o)
    oos.close()
    bos.toByteArray
  }
  //反序列化
  def deserialize[T](bytes:Array[Byte]):T={
    val bis=new ByteArrayInputStream(bytes)
    val ois=new ObjectInputStream(bis)
    ois.readObject.asInstanceOf[T]//进行类型转换,因为你要返回这个类型
  }
  
  //文件输出流
  def serialize_file[T](o:T)={
    val bos = new FileOutputStream("D:\\a.txt")
    val oos = new ObjectOutputStream(bos)
    oos.writeObject(o)
    oos.close()
  }
  //文件输入流
  def deserialize_file[T](file:String):T={
    val bis=new FileInputStream(file)
    val ois=new ObjectInputStream(bis)
    ois.readObject.asInstanceOf[T]//进行类型转换,因为你要返回这个类型
  }
   
  
  
  
  
  
  
  
  
  
  
  
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM