java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java序列化和反序列化

Java基础入门总结之序列化和反序列化

作者:攻城狮Chova

序列化是一种对象持久化的手段,普遍应用在网络传输、RMI等场景中,下面这篇文章主要给大家介绍了关于Java基础入门总结之序列化和反序列化的相关资料,需要的朋友可以参考下

基本概念

序列化

public class Person implements Serializable {
	private String name;
	private int age;

	public Person() {
		System.out.println("无参构造...");
	}

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
		System.out.println("有参构造...");
	}

	@Override
	public String toString() {
		return "Person{" +
				"name='" + name + "\'" +
				", age='" + age + "\'"
				"}";
	}
}
public class SerializableTest {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		Person person = new Person("Lily", 20);

		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Person.txt"));
		oos.writeObject(person);
		oos.close();
	}
}

反序列化

public class  DeserializableTest {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Person.txt"));
		Pesron person = (Person)ois.readObject(ois);
		System.out.println(person);
	}
}

序列化和反序列化总结

自定义序列化策略

Externalizable

public class CustomExternal implements Externalizable {
	
	private String name;
	
	private int code;

	public CustomExternal() {
		System.out.println("无参构造...");
	}
	
	public CustomExternal(String name, int code) {
		this.name = name;
		this.code = code;
		System.out.println("有参构造...");
	}

	@Override
	public void writeExternal(ObjectOutput out) throws IOException {
		System.out.println("执行writeExternal()方法...");
		out.writeObject(name);
		out.writeInt(code);
	} 

	@Override
	public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
		System.out.println("执行readExternal()方法...");
		name = (String) in.readObject();
		code = in.readInt();
	}

	@Override
	public String toString() {
		return "类:" + name + code;
	}

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		CustomExternal custom = new CustomeExternal("oxford", 666);
		System.out.println(custom);
		
		// 序列化
		ObjectOutputStream out = new ObjectOutputStream(new FileInputStream("oxford.txt"));
		System.out.println("序列化对象...");
		out.writeObject(custom);
		out.close();

		// 反序列化
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("oxford.txt"));
		System.out.println("反序列化对象...");
		custom = (CustomExternal) in.readObject();
		System.out.println(custom);
		in.close();
	}
}

有参构造...
类:oxford666
序列化对象...
执行writeExternal()方法...
反序列化对象...
无参构造...
执行readExternal()方法...
类:oxford666 

transient

静态变量

序列化ID

破坏单例

总结

到此这篇关于Java基础入门之序列化和反序列化的文章就介绍到这了,更多相关Java序列化和反序列化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文