java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE, JavaME, JavaSE)的总称。本站提供基于Java框架struts,spring,hibernate等的桌面应用、web交互及移动终端的开发技巧与资料

保持永久学习的心态,将成就一个优秀的你,来 继续搞起java知识。

//对象序列化
	//所谓对象序列化,即把一个对象,变为二进制
	//对象所在的类,须实现Serializable接口
	public static void main(String[] args) throws Exception {
		ObjectOutputStream objectOutput=
				new ObjectOutputStream(new FileOutputStream(new File("d:"+File.separator+"t2.txt")));
		objectOutput.writeObject(new Person("Lee", 11));
	}
//反序列化
	public static void main(String[] args) throws Exception {
		ObjectInputStream objectInputStream = 
				new ObjectInputStream(new FileInputStream(new File("d:"+File.separator+"t2.txt")));
		
		Object object = objectInputStream.readObject();//读取对象
		objectInputStream.close();
		System.out.println(object);

//序列化,需要实现Serializable接口
class Person3 implements Serializable {
	private int age;
	private String name;

	@Override
	public String toString() {
		return "Person3 [age=" + age + ", name=" + name + "]";
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

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

}

public class T19 {
	//序列化一组对象
	public static void main(String[] args) throws Exception {
		Person3[] pers = { new Person3(11, "Lee"), new Person3(22, "qwere"), new Person3(55, "xiao"), };

		ser(pers);
		Object[] objects = deser();
		for (int i = 0; i < objects.length; i++) {
			Person3 p = (Person3) objects[i];
			System.out.println(p);
		}
	}

	//序列化
	public static void ser(Object[] obj) throws Exception {
		ObjectOutputStream objectOutputStream = new ObjectOutputStream(
				new FileOutputStream(new File("d:" + File.separator + "ser.txt")));

		objectOutputStream.writeObject(obj);
		objectOutputStream.close();//关闭输出
	}

	//反序列化
	public static Object[] deser() throws Exception {
		ObjectInputStream objectInputStream = new ObjectInputStream(
				new FileInputStream(new File("d:" + File.separator + "ser.txt")));

		Object[] obj = (Object[]) objectInputStream.readObject();//读取对象数组
		objectInputStream.close();
		return obj;
	}
}

因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。

后续会有更多的精彩的内容分享给大家。