当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
2015年计算机二级考试JAVA知识点整理(42)
发布时间:2010/12/14 15:02:37 来源:城市学习网 编辑:ziteng
  1.3.8 对象流
  串行化:对象通过写出描述自己状态的数值来记述自己的过程叫串行话
  对象流:能够输入输出对象的流
  将串行化的对象通过对象流写入文件或传送到其他地方
  对象流是在普通流上加了传输对象的功能,所以构造对象流时要先构造普通文件流
  注意:只有实现了Serializable接口的类才能被串行化
  例子:
  import java.io.*;
  class Student implements Serializable{
  private String name;
  private int age;
  public Student(String name,int age){
  this.name=name;
  this.age=age;
  }
  public void greeting(){
  System.out.println("hello ,my name is "+name);
  }
  public String toString(){
  return "Student["+name+","+age+"]";
  }
  }
  public class ObjectOutTest{
  public static void main(String args[]){
  ObjectOutputStream oos=null;
  try{
  oos=new ObjectOutputStream(
  new FileOutputStream("student.txt"));
  Student s1=new Student("Jerry",24);
  Student s2=new Student("Andy",33);
  oos.writeObject(s1);
  oos.writeObject(s2);
  }catch(Exception e){
  e.printStackTrace();
  }finally{
  if(oos!=null)
  try{
  oos.close();
  }catch(Exception e){
  e.printStackTrace();
  }
  }
  }
  }
  import java.io.*;
  public class ObjectInTest{
  public static void main(String args[]){
  ObjectInputStream ois=null;
  Student s=null;
  try{
  ois=new ObjectInputStream(
  new FileInputStream("student.txt"));
  System.out.println("--------------------");
  s=(Student)ois.readObject();
  System.out.println(s);
  s.greeting();
  System.out.println("--------------------");
  s=(Student)ois.readObject();
  System.out.println(s);
  s.greeting();
  }catch(Exception e){
  e.printStackTrace();
  }finally{
  if(ois!=null)
  try{
  ois.close();
  }catch(Exception e){
  e.printStackTrace();
  }
  }
  }
  }
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved