java 对象 序列化 文件中_java将序列化对象存到文件中

如何将一个对象以序列化的方式写到文件中呢,请看下面代码:

首先创建一个类,若想该类能以序列化的方式写到流中,必须实现Serializable

import java.io.Serializable;

public class Person implements Serializable{

private String name = "";

private int age = 0;

private String phone = "";

private Clothes clothes = null;

public Person(String name, int age, String phone, Clothes clothes){

this.name = name;

this.age = age;

this.phone = phone;

this.clothes = clothes;

}

public void disString(){

System.out.println("name: " + name + "; age: " + age + "; phone: " + phone);

}

}

注意,该类中有一个Clothes对象,该类的代码实现如下:

public class Clothes {

private int id = 0;

public Clothes(int id){

this.id = id;

}

}

现在通过ObjectOutputStream将Person类的对象写到流中,再用FileOutputStream将流写到文件中:

Person person = new Person("lisi", 10, "12345678", new Clothes(11));

try {

ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("person.dat"));

objectOutputStream.writeObject(person);

ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("person.dat"));

Person pre = (Person)objectInputStream.readObject();

per.disString();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

运行,结果如下:

f2ceef5fdbb807db6346b451b769041b.png

程序抛出异常,为什么呢?我们注意到,Person类中有一个成员变量是Clothes类的,但该类没有并没有实现Serializable。所以再序列化clothes成员的时候抛出异常。

解决方式:

若希望将clothes成员变量也序列化,那必须让Clothes类实现Serializable。

public class Clothes implements Serializable{

若不希望clothes成员变量也序列化,则在声明该变量的时候加上transient关键字。序列化的时候将跳过该成员:

private transient Clothes clothes = null;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值