Java Serializable 详解

package com.java.serializable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * JAVA序列化详解
 * @author yfding
 *
 */
public class SerializableTest {
	public static void main(String[] args) {
		/**
		 * 基本概念
		 * 1.把对象转换成字节序列的过程称为对象的序列化
		 * 2.把字节序列转换成对象的过程称为对象的反序列化
		 * 
		 * 序列化的用途
		 * 1.把对象保存到硬盘上
		 * 2.网络传输中
		 * 
		 * 注意点
		 * 1.如果Student对象为实现Serializable接口,出现异常【java.io.NotSerializableException: com.java.serializable.Student】
		 * 2.serialVersionUID是java编译器运行时根据java类自动生成的,建议在序列化类对象时生成serialVersionUID
		 * 3.如果不生成serialVersionUID,当我们在类中新增方法,或者属性时,在反序列化时,java会重新生成一个新的serialVersionUID,导致之前序列化的文件不能被反序列化
		 * */
		
		// 序列化Student对象
		SerializableTest.SerializeStudent();
		
		// 反序列化Student对象
		SerializableTest.DeserializeStudent();
		
	}
	
	/** 序列化Student */
	private static void SerializeStudent(){
		Student student = new Student("yfding",18);
		try {
			ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("C:/admin-pc/Student.txt")));
			oos.writeObject(student);
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("序列化Student对象失败。");
			return;
		}
		System.out.println("序列化Student对象成功。");
	}
	
	private static void DeserializeStudent(){
		Student student = null;
		try {
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("C:/admin-pc/Student.txt")));
			student = (Student) ois.readObject();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("反序列化Student对象失败。");
			return;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("反序列化Student对象失败。");
			return;
		}
		System.out.println("反序列化Student对象成功。Student-toString()----"+student.toString());
	}
}

class Student implements Serializable{
	private static final long serialVersionUID = -231956256888721831L;
	private String name;
	private int age;
	/*private int sex;
	
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}*/
	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;
	}
	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值