JAVA--Object(对象序列化)

(一)定义

把一个Object对象直接转化为字节流,让后把字节流直接写入本地硬盘或者网络中;

如果需要对某个对象实现序列化,必须实现Serializable接口;(Serialzable为空接口,起标识作用)

transient修饰的成员无法被序列化;

public class TestObjectIO
{
	public static void main(String[] args)
	{
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null; 
		Student ss = new Student("zhansan", 1000, 88.8f);  //注意88.8f不能改为88.8 
		Student ss2 = null;	
				
		try
		{
			FileOutputStream fos = new FileOutputStream("d:/share/java/ObjectOut.txt");
			oos = new ObjectOutputStream(fos);
			oos.writeObject(ss);
			
			ois = new ObjectInputStream(new FileInputStream("d:/share/java/ObjectOut.txt"));	
			ss2 = (Student)ois.readObject();  //(Student)不能省   ois.readObject();如果ois中的某个成员是transient,则该成员是不会被读取的,因为该成员不会被保存,何来读取之说?!
			
			System.out.println("ss2.sname = " + ss2.sname);
			System.out.println("ss2.sid = " + ss2.sid);
			System.out.println("ss2.sscore = " + ss2.sscore);
		}
		catch (FileNotFoundException e)
		{
			System.out.println("文件没有找到!");
			System.exit(-1);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(-1);
		}
		finally
		{
			try
			{
				oos.close();
				ois.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
				System.exit(-1);
			}
		}		
	}
}

class Student implements Serializable  //如果将implements Serializable 注释掉,则程序编译时就会报错
{
	public String sname = null;
	public int sid = 0;
	transient public float sscore = 0; //表示sscore成员不能被序列化,所谓不能被序列化就是指:“该成员调用ObjectOutputStream 的writeOnbject()时不会被保存,调用ObjectInputStream的readObject()方法时不会被读取”
	
	public Student(String name, int id, float score)
	{
		this.sname = name;
		this.sid = id;
		this.sscore =  score;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值