java序列化对象简单例子,Java序列化的一个例子

学习Java这么久,虽然脑子中有关于序列化的理解,但没实际应用过,刚好碰到朋友要帮忙做个作业,就趁机写一个很简单的例子。

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

/**

* 对象的序列化主要有两种用途:

1) 把对象的字节序列永久地保存到硬盘上,通常存放在一个文件中;

2) 在网络上传送对象的字节序列。

*/

/**

* 要使对象序列化,就令该对象继承java.io.Serializable类。

*/

/**

* @author Jim

* @Time 2016年4月14日 下午1:47:48

*

*/

public class Program21 {

public static void main(String[] args){

try{

//序列化对象,将对象保存在student.dat中

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.dat"));

Student s1 = new Student("Lisa", 20);

out.writeObject(s1);//写入对象

out.close();

//将student.dat中的对象反序列化并print information.

ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.dat"));

Student s2 = (Student)in.readObject();//读出对象

System.out.print("Student's name is " + s2.getName() + " and the age is " + s2.getAge());

in.close();

}catch(Exception e){

e.printStackTrace();

}

}

}

/**

* 定义一个学生类来继承java.io.Serializable

*/

class Student implements Serializable {

private String name = "";

private int age = 0;

public Student(String name, int age) {

this.name = name;

this.age = age;

}

public String getName(){

return this.name;

}

public int getAge() {

return this.age;

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值