java对象序列化示例

java对象序列化示例

序列化:处理对象流的机制,所谓对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。序列化是为了解决在对对象流进行读写操作时所引发的问题。
序列化的实现:

将需要被序列化的类实现Serializable接口,该接口没有需要实现的方法,implements Serializable只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。

Static 和transient修饰的不能被序列化

下面展示两个实例


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class TestAnotherSerialize {
	public static void main(String[] args) throws IOException,
	ClassNotFoundException {
		// 1. 准备数据
		List dataList = new ArrayList();
		dataList.add("abc");
		dataList.add("123");
		// 2. 构造序列化流
		String sFilePath = "f://serializeDemo/test_another_serialize.dat";
		FileOutputStream fos = null;
		ObjectOutputStream ooS = null;
		try {
			fos = new FileOutputStream(sFilePath);
			ooS = new ObjectOutputStream(fos);
			ooS.writeObject(dataList);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (fos != null)
				fos.close();
			if (ooS != null) {
				ooS.close();
			}
		}
		// 3. 从序列化文件中读取出文件
		FileInputStream fiStream = null;
		ObjectInputStream oiStream = null;
		try {
			fiStream = new FileInputStream(sFilePath);
			oiStream = new ObjectInputStream(fiStream);
			List serializeResult = (List) oiStream.readObject();
			System.out.println(" 序列化结果为::" + serializeResult);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (fiStream != null)
				fiStream.close();
			if (oiStream != null) {
				oiStream.close();
			}
		}
	}
}
输出结果: 序列化结果为::[abc, 123]



import java.io.Serializable;

public class SerializeStudent implements Serializable {	 
    /**
      * 序列化对象的标识,用于在反序列化的时候使用 
      * 反序列化的时候,如果当前内存中已经有这个标识的对象,则认为是同一类对象
      */
    private static final long serialVersionUID = -6193310436318894856L;
    /* 演示瞬时态对象不会被序列化 */
    private transient String age = null ;
    /* 成员属性 */
    private String studentName = null ;
    public static String dept = null ; 
    public void setStudentName(String studentName) {
       this.studentName = studentName;
    }
    public void setDept(String deptt) {
       this.dept = deptt;
    }
    public void setAge(String age) {
       this.age = age;
    }
    @Override
    public String toString() {
    	return " 学生姓名: " + studentName + ", 系 ( 静态字段 ) : " + dept + ", 年龄( 瞬时态字段 ) : "
                + age ;
      }
}


//测试类

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class TestSerialize {
	public static void main(String[] args) throws IOException,
			ClassNotFoundException {
		// 1. 序列化文件保存的地址
		String filePath = "F://serializeDemo/test_serialize.oo";
		// 2. 序列化对象到文件中
		testWriteObject(filePath);
		// 读取字段
		testReadObject(filePath);
	}
	/**
	 * 序列化一个 stu 对象到文件中
	 * @throws IOException
	 */
	private static void testWriteObject(String filePath) throws IOException {
		// 1. 构造 SerializeStudent 对象
		SerializeStudent stu = new SerializeStudent();
		stu.setStudentName("wuguowei"); // 非瞬时态又是非静态字段,所以肯定会序列化
		stu.setDept("computer "); // dept 是 static
										// ,这里不会被序列化,如果被序列化的话,那么值应该为 computer
		stu.setAge("04133"); // 由于 class 是 transient ,所以不会被序列化
		// 2. 构造序列化流
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream(filePath);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(stu);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (fos != null)
				fos.close();
			if (oos != null) {
				oos.close();
			}
		}
		// 3. 还原静态字段,以免影响测试
		stu.setDept(null);
	}
	/**
	 * 从序列化文件中读取出 serializeStudent 对象
	 * @throws IOException
	 */
	private static void testReadObject(String filePath) throws IOException {
		// 1. 从序列化文件中读取出文件
		FileInputStream fiStream = null;
		ObjectInputStream oiStream = null;
		try {
			fiStream = new FileInputStream(filePath);
			oiStream = new ObjectInputStream(fiStream);
			// 读取信息
			SerializeStudent readStudent = (SerializeStudent) oiStream
					.readObject();
			System.out.println(" 当前学生信息 ::" + readStudent);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (fiStream != null)
				fiStream.close();
			if (oiStream != null) {
				oiStream.close();
			}
		}
	}
}
输出结果:  当前学生信息 :: 学生姓名: wuguowei, 系 ( 静态字段 ) : null, 年龄( 瞬时态字段 ) : null




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值