0
点赞
收藏
分享

微信扫一扫

对象序列化流和对象反序列化流的学习记录

知年_7740 2022-04-06 阅读 89

对象序列化流:
 

package io;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/*
 *  对象序列化流:ObjectOutputStream
	构造方法:
	ObjectOutputStream(OutputStream out):创建一个写入指定的OutputStream的ObjectOutputStream
	序列化对象的方法:
	void writeObject(Objectobj):将指定的对象写入ObjectOutputStream
	注意:
	一个对象要想被序列化,该对象所属的类必须必须实现Serializable接口
	 Serializable是一个标记接口,实现该接口,不需要重写任何方法

 */
public class ObjectOutputStreamdemo {
	public static void main(String[] args) throws IOException {
	//ObjectOutputStream(OutputStream out):创建一个写入指定的OutputStream的ObjectOutputStream
		ObjectOutputStream oos =new ObjectOutputStream(new FileOutputStream("C:\\DW\\fis.txt"));
	//创建对象
	Student s =new Student("001","xx","dd","12");
	//void writeObject(Objectobj):将指定的对象写入ObjectOutputStream
	    oos.writeObject(s);
	   //释放资源
	    oos.close();
		
	}

}

对象反序列化流:
 

package io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

/*
 * 对象反序列化流:ObjectInputStream
    ObjectInputStream反序列化先前使用ObjectOutputStream编写的原始数据和对象
    
	构造方法:ObjectInputStream(InputStream in):创建从指定的InputStream读取的ObjectinputStream	
	反序列化对象的方法:Object readObject():从ObjectInputStream读取一个对象
 */
public class ObiectinputStreamdemo {
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		//构造方法:ObjectInputStream(InputStream in):创建从指定的InputStream读取的ObjectinputStream	
		ObjectInputStream ois =new ObjectInputStream(new FileInputStream("C:\\DW\\fis.txt"));
		//	反序列化对象的方法:Object readObject():从ObjectInputStream读取一个对象
         Object obj=ois.readObject();
         Student s=(Student)obj;
         System.out.println(s.getsid()+","+s.getname()+","+s.getaddress()+","+s.getage());
         ois.close();
	}
}
举报

相关推荐

0 条评论