ObjectOutuptStream out = null; try { out = new ObjectOutputStream(new FileOutputStream("foo.ser")); out.writeObject(foo); } catch (FileNotFoundException e) { handleError(e); } catch (IOException e) { handleError(e); } finally { try { if (out != null) { out.flush(); out.close(); } } catch (IOException e) { } } デシリアライゼーション(復元) Foo foo = null; ObjectInputStream in = null; try { in = new ObjectInputStream(new FileOutputStream("foo.ser")); foo = (Foo)in.readObject(); } catch (FileNotFoundException e) { handleError(e); } catch (OptionalDataException e) { handleError(e); } catch (ClassNotFoundException e) { handleError(e); } catch (IOException e) { handleError(e); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { } } ObjectWriterとReaderの拡張 "T.Ikura" <ikura@nagoya.iij.ad.jp> writes:
なるほど、ObjectInputStreamの方もheaderを読まないようにしたのですか。 こちらの意図としては、 ・最初の一回は普通のObjectOutputStreamでwriteObjectして、 ・appendするときはNonHeaderObjectOutputStreamでwriteObjectして、 ・読むときは普通のObjectInputStreamでreadObjectする。 というものでした。 headerなしでも動いてしまうのですね。headerはmagic番号とversion番号の チェックをしているだけなのですね。取ってしまってもいいといえばいいかも しれないですが、他のアプリケーションと組み合わせる可能性を考えると、 上のようにheaderを付けるようにした方がいいかも。 「最初の一回」かどうかで場合分けするのがあれでしたら、「ファイルを作る」 という操作で、 new ObjectOutputStream(new FileOutputStream(filename)).close(); として、headerだけのファイルを作り、 「オブジェクトを追加書き出しする」という操作で、 ObjectOutput oo = new NonHeaderObjectOutputStream( new FileOutputStream(filename, true) ); oo.writeObject(... とすればよいのではないかと。 String dirname="."+File.separator+"savedat"; load.removeAllItems(); File dir=new File(dirname); String[] filelist=dir.list(); for(int i=0;i<filelist.length;i++){ if(Pattern.matches(".*\\.dat$",filelist[i])){ load.addItem(filelist[i]); } |