什么是Java序列化?

什么是Java序列化,如何实现java序列化

package cn.itcast.demo2;

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.io.Serializable;

public class People implements Serializable{
	private String name;
	private int age;
	public People(){
		this.name = "lili";
		this.age = 20;
	}
	
	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	/**
	 * java.io.ObjectOutputStream代表对象输出流
	 * 它的writeObject(Object obj)方法可对参数指定的obj对象进行序列化
	 * 把得到的字节序列写到一个目标输出流中。
	 * 只有实现了Serializable和Externalizable接口的类的对象才能被序列化。
	 * @param args
	 */
	public static void main(String[] args) {
		People p = new People();
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;		
		try {
			//序列化对象
			FileOutputStream fos = new FileOutputStream("perple.out");
			oos = new ObjectOutputStream(fos);
			oos.writeObject(p);
			oos.close();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
		People p1;
		/**
		 * java.io.ObjectInputStream代表对象输入流
		 * 它的readObject()方法从一个源输入流中读取字节序列
		 * 再把它们反序列化为一个对象,并将其返回。
		 */
		try {
			//反序列化对象
			FileInputStream fis = new FileInputStream("perple.out");
			ois = new ObjectInputStream(fis);
			p1 = (People) ois.readObject();
			System.out.println("name:" + p1.getName());
			System.out.println("age:" + p1.getAge());
			ois.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}		
	}

}

什么是Java序列化?_第1张图片

package cn.itcast.demo2;

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

public class ObjectSaver {
	public static void main(String[] args) {
		/*其中的 "perple.out" 表示存放序列化对象的文件*/
		//序列化对象
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;		
		try {
			FileOutputStream fos = new FileOutputStream("perple.out");
			oos = new ObjectOutputStream(fos);
			Customer customer = new Customer("王麻子", 24);
			oos.writeObject("你好!");
			oos.writeObject(new Date());
			oos.writeObject(customer);
			oos.close();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		Customer obj3 = null;
		//反序列化对象
		try {
			FileInputStream fis = new FileInputStream("perple.out");
			ois = new ObjectInputStream(fis);
			System.out.println("obj1 " + (String) ois.readObject());    //读取字面值常量
			System.out.println("obj2 " + (Date) ois.readObject());    //读取匿名Date对象
			obj3 = (Customer) ois.readObject();    //读取customer对象
			System.out.println("obj3 " + obj3);
			ois.close();
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
		}
		
	}
}

什么是Java序列化?_第2张图片

你可能感兴趣的:(程序员面试笔记)