java序列化和反序列化的简单实例

先创建一个实体类,实现Serializable接口

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

	public String getName() {
		return name;
	}

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

}

再创建一个序列化和反序列化的工具类

public class SerializationUtil {
	
	//.bin后缀代表二进制文件
	private static String FILE_NAME = "D:/obj.bin";
	
	/**
	 * 序列化
	 */
	public static void writeObject(Serializable s) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME));
			oos.writeObject(s);
			oos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 反序列化
	 */
	public static Object readObject() {
		Object obj = null;
		
		try {
			ObjectInput input = new ObjectInputStream(new FileInputStream(FILE_NAME));
			obj = input.readObject();
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
}

然后main方法测试

public class Main {

	public static void main(String[] args) {
		
		//序列化
		Person person = new Person();
		person.setName("混世魔王");
		SerializationUtil.writeObject(person);
		
		Person p = (Person) SerializationUtil.readObject();
		System.out.println("name = " + p.getName());
	}

}

你可能感兴趣的:(java)