java.io.Serializable序列化

    java.io.Serializable的本质就是将内存的对象,以文本的形式保存到磁盘上,使用的时候再读出来,以减少应用程序的压力.有点类似与虚拟内存.在openJPA里,entity的时候,一般需要使用.
    序列化的时候有以下几点需要注意.
1)先序列化,先读取(FIFO);
2)反序列化的时候,返回的都是Object,要自动转换类型;
3)用关键字transient标记的属性,将不被序列化;
4)对象要继承类java.io.Serializable;
5)序列化用ObjectOutputStream,反序列化用ObjectInputStream;
    下面是2个示例代码,一看就能明白,本人不做过多的解释^_^

package test;

import java.io.Serializable;

public class User implements Serializable {
	private String name;
	private transient int age;

	public User(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String toString() {
		return "name=" + name + "\n" + "age=" + age;
	}
}



package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

public class TestSerializable {

	public static void main(String[] args) {
		String path = "c:\\myfile";
		serialize(path);
		System.out.println("Object is serializing!");
		deSerialize(path);
	}

	public static void serialize(String fileName) {
		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(fileName));
			out.writeObject("phl");// 序列化字符串对象
			out.writeObject(new Date());// 序列化日期对象
			User user = new User("phl", 26);
			out.writeObject(user);// 序列化自定义对象
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void deSerialize(String fileName) {
		try {
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
			String name = (String) in.readObject();
			Date date = (Date) in.readObject();
			User user = (User) in.readObject();
			System.out.println(name);
			System.out.println(date);
			System.out.println(user.toString());
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}


运行结果:
Object is serializing!
phl
Fri Sep 03 19:44:47 CST 2010
name=phl
age=0

你可能感兴趣的:(java)