| 发表于:2007-06-28 02:54:2813楼 得分:0 |
如果实现了serializable 然后直接用objectouputstream.writeobject(object obj) 读进来的时候用object objectinputstream.readobject() 这个东西比较有意思,特别是写树这些有很多层的组件,非常好用. 下面是最简单的把一个jbutton的对象写入到硬盘里,然后读取出来,再显示在jframe上,因为jbutton已经实现了serializable,所以就不用再实现了,自己写了一下,复习一下,好久没弄过了,呵呵: import java.io.*; import javax.swing.*; public class writeobject { public static void main(string[] args) { objectoutputstream oos = null; objectinputstream ois = null; try { fileoutputstream fos = new fileoutputstream( "obj.dat "); oos = new objectoutputstream(fos); jbutton button = new jbutton( "my button "); oos.writeobject(button); oos.close(); oos = null; fileinputstream fis = new fileinputstream( "obj.dat "); ois = new objectinputstream(fis); jbutton button2 = (jbutton)ois.readobject(); ois.close(); ois = null; jframe frame = new jframe( "example "); frame.getcontentpane().add(button2); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(400, 400); frame.setvisible(true); } catch(ioexception ioex) { system.out.println(ioex.getmessage()); } catch(classnotfoundexception cnex) { system.out.println(cnex.getmessage()); } finally { try { if (oos != null) oos.close(); if (ois != null) ois.close(); } catch(ioexception ioex2) { } } } } | | |
|