2011年计算机二级考试JAVA知识点整理(26)

2014-10-31 21:30:09 · 作者: · 浏览: 72

  1.1.3.2.9 串行化


  串行化 以标准格式将任意的Java数据结构转换为字节流。例如,下面的程序输出随机整数数组:


  import java.io.*;


  import java.util.*;


  public class serial1 {


  public static void main(String args[]) {


  ArrayList al = new ArrayList();


  Random rn = new Random();


  final int N = 100000;


  for (int i = 1; i <= N; i++)


  al.add(new Integer(rn.nextInt()));


  try {


  FileOutputStream fos = new FileOutputStream("test.ser");


  BufferedOutputStream bos = new BufferedOutputStream(fos);


  ObjectOutputStream oos = new ObjectOutputStream(bos);


  oos.writeObject(al);


  oos.close();


  } catch (Throwable e) {


  System.err.println(e);


  }


  }


  }


  而下面的程序读回数组:


  import java.io.*;


  import java.util.*;


  public class serial2 {


  public static void main(String args[]) {


  ArrayList al = null;


  try {


  FileInputStream fis = new FileInputStream("test.ser");


  BufferedInputStream bis = new BufferedInputStream(fis);


  ObjectInputStream ois = new ObjectInputStream(bis);


  al = (ArrayList) ois.readObject();


  ois.close();


  } catch (Throwable e) {


  System.err.println(e);


  }


  }


  }