二级JAVA第六章辅导:Java串行化 |
|
www.nanhushi.com 佚名 不详 |
1. 串行化例子一 ObjectInputStream和ObjectOutputStream。
public class SerializationDemo {
public static void main(String[] args) { // TODO Auto-generated method stub try { Vector list;
BufferedReader reader = new BufferedReader(new InputStreamReader( System.in)); System.out.print("Checking for previous serialized list");
try { FileInputStream fin = new FileInputStream("list.out");
ObjectInputStream oin = new ObjectInputStream(fin);
try { Object obj = oin.readObject(); list = (Vector) obj;
} catch (ClassCastException e) { // TODO: handle exception list = new Vector(); } catch (ClassNotFoundException e){ list = new Vector(); } fin.close();
} catch (FileNotFoundException e) { // TODO: handle exception list = new Vector(); } for (;;){ System.out.println("Menu :-"); System.out.println("1.. Add item"); System.out.println("2.. Delete item"); System.out.println("3.. List items"); System.out.println("4.. Save and quit"); System.out.println("Choice"); String response = reader.readLine(); int choice = Integer.parseInt(response); switch (choice) { case 1: System.out.print("Enter item : "); String item = reader.readLine(); list.addElement(item);
break; case 2: System.out.print("Enter item : "); String deadItem = reader.readLine(); list.removeElement(deadItem); break; case 3: for (Enumeration e = list.elements(); e.hasMoreElements(); ){ System.out.println(e.nextElement()); } break; case 4: System.out.println("Saving list"); FileOutputStream fout = new FileOutputStream("list.out"); ObjectOutputStream oout = new ObjectOutputStream(fout); oout.writeObject(list); fout.close(); System.exit(0); break; default: break; } } } catch (IOException e) { // TODO: handle exception System.out.print("I/O error."); } }
} 2.用transient声明需要保密的变量。 在串行化过程中,忽略此类变量。 实现java.io.Serializable 接口。
|
|
|
文章录入:杜斌 责任编辑:杜斌 |
|
上一篇文章: 二级JAVA第六章辅导:对象串行化 下一篇文章: Java语言的接口与类型安全 |
【字体:小 大】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口】 |
|
|