ObjectInputStream和ObjectOutputStream


1.

      ObjectInputStream与ObjectOutputStream类所读写的对象必须实现Serializable接口,ObjectOutputStream是把对象堆中的数据存写到文件中,所以对象中的transient和static类型成员变量不会被读取和写入;

注意:如果没有实现Serializable接口,则出错。这是为了保证能把对象写入到文件,并能再把对象读回到程序中的缘故。

      对数据其中转作用的是文件,ObjectOutputStream把对象存入文件,  ObjectInputStream从文件中读取数据

2. 
 import java.io.*;
public class serializtion {
 
 public static void main(String[] args)throws IOException{
  Student s1=new Student("wangwu", 1, 18, "数学");        //要被存储的对象
  Student s2=new Student("lisi", 2, 19, "物理");
 

//把对象存入文件中

  FileOutputStream fout=new FileOutputStream("student.txt");

  ObjectOutputStream out=new ObjectOutputStream(fout);
  out.writeObject(s1);
  out.writeObject(s2);

  out.close();

//从文件中读取对象

  FileInputStream fin=new FileInputStream("student.txt");
  ObjectInputStream in=new ObjectInputStream(fin);
  try {
   s1=(Student) in.readObject();
   s2=(Student) in.readObject();
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    in.close();
    System.out.print("name:"+s1.name);
    System.out.print(" id:"+s1.id);
    System.out.print(" age:"+s1.age);
    System.out.println(" department:"+s1.department);
    System.out.print("name:"+s2.name);
    System.out.print(" id:"+s2.id);
    System.out.print(" age:"+s2.age);
    System.out.println(" department:"+s2.department);
 }
}

3.import java.io.*;

//要存入的对象所属的类

public class Student implements Serializable {
 
        String name;
        int id ;
        int age;
        String department;
  public Student(String name, int id, int age, String department) {
   this.age = age;
   this.department = department;
   this.id = id;
   this.name = name;
  }

 }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值