注意:要 extends Serializable才能序列化
package kang
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.ObjectOutputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.FileInputStream
import scala.io.Source
class DTBag extends Serializable {
var name="spark"
}
object Scala_io {
def main(args:Array[String]):Unit={
val bag=new DTBag
val a= serializeToStorage(bag)//输出到内存
println(serializeFromStorage(a))//从内存中读取
val location="C://Users//Administrator//Desktop//1.txt"
val b=serializeToDisk(bag,location)//输出到硬盘
println(serializeFromDisk(location))//从硬盘读取
//使用封装的工具
for(line <- Source.fromFile(location,"GBK").getLines()){
println(line)
}
}
//输出到内存
def serializeToStorage[T](o:T):Array[Byte]={
val boo=new ByteArrayOutputStream()
val oos=new ObjectOutputStream(boo)
oos.writeObject(o)
oos.close
boo.toByteArray
}
//从内存中读取
def serializeFromStorage(array:Array[Byte])={
val ois=new ObjectInputStream(new ByteArrayInputStream(array))
val result=ois.readObject()
ois.close
result
}
//输出到硬盘
def serializeToDisk[T](o:T,location:String)={
val fos=new FileOutputStream(location)
val oos=new ObjectOutputStream(fos)
oos.writeObject(o)
oos.close
}
//从硬盘读取
def serializeFromDisk(location:String)={
val ois=new ObjectInputStream(new FileInputStream(location))
val result=ois.readObject()
ois.close
result
}
}