Java 序列化与反序列化 —— 序列化为一般二进制格式文件

Step1:创建一个实现了Serializable接口的类

import java.io.Serializable;

public class Person implements Serializable {
	private static final long serialVersionUID = 172447632608611914L;
	private String name;
	private int age;

	public Person() {

	}

	public Person(String name, int age) {
		System.out.println("Inside Person's Constructor");
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

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

}

Step2:通过ObjectOutputStream对象序列化保存数据

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

public class WritePerson {

	public static void main(String[] args) throws IOException {
		FileOutputStream outFile = null;
		ObjectOutputStream out = null;
		try {
			String path = "src/myPerson.bin";
			outFile = new FileOutputStream(path);
			out = new ObjectOutputStream(outFile);

			Person person = new Person("张三", 20);
			out.writeObject(person);
			System.out.println("序列化对象成功");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (outFile != null)
				outFile.close();
			if (out != null)
				out.close();
		}
	}
}

Step3:通过ObjectInputStream对象反序列化数据为实例对象

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

public class ReadPerson {

	public static void main(String[] args) throws IOException,
			ClassNotFoundException {
		String path = "src/myPerson.bin";
		FileInputStream fileIn = null;
		ObjectInputStream in = null;
		try {
			fileIn = new FileInputStream(path);
			in = new ObjectInputStream(fileIn);
			Person person = (Person) in.readObject();
			if (person != null) {
				System.out.println(person);
			} else {
				System.out.println("反序列化对象失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fileIn != null)
				fileIn.close();
			if (in != null)
				in.close();
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值