XMLへの永続化サンプル
XMLへの永続化の記事があったのでちょっとちょっと試してみた。
Beanを出力して入力するだけの簡単なサンプル。
材料はこのあたり
XStream
import com.thoughtworks.xstream.XStream; public class SerializeExample { /** * ファイルパス */ private static final String XML_PATH = "./test.xml"; /** * * 実行 * @throws Exception 例外 */ public void execute() throws Exception { output(); input(); } /** * * オブジェクトをXMLに変換します。 * @throws IOException 例外 */ private void output() throws IOException { Writer writer = null; try { final Test test = new Test(); test.setHoge("hoge"); test.setPiyo("piyo"); writer = new FileWriter(XML_PATH); final XStream xstream = new XStream(); xstream.toXML(test, writer); } finally { writer.close(); } } /** * * XMLとオブジェクトに変換します。 * @throws IOException 例外 * @throws FileNotFoundException 例外 */ private void input() throws IOException, FileNotFoundException { Reader reader = null; BufferedReader br = null; try { reader = new FileReader(XML_PATH); br = new BufferedReader(reader); final XStream xstream = new XStream(); final Test test = (Test)xstream.fromXML(br); System.out.println(test.getHoge()); System.out.println(test.getPiyo()); } finally { br.close(); reader.close(); } } /** * * <HR> * <P> * ■モジュール名 <BR> * <BLOCKQUOTE> * Test.java <BR> * </BLOCKQUOTE> * <P> * ■クラス仕様 <BR> * <BLOCKQUOTE> * Testクラスはxxxxするクラスです。<BR> * </BLOCKQUOTE> * <P> * <HR> * <P> */ public static class Test { /** * 確認用メンバ */ private String hoge; /** * 確認用メンバ */ private String piyo; /** * を取得します。 * @return */ public String getHoge() { return hoge; } /** * を設定します。 * @param hoge */ public void setHoge(String hoge) { this.hoge = hoge; } /** * を取得します。 * @return */ public String getPiyo() { return piyo; } /** * を設定します。 * @param piyo */ public void setPiyo(String piyo) { this.piyo = piyo; } } }