SewiGの日記
2005-11-15 [火] [長年日記]
■ [Java][Programming] オブジェクトをファイルへ書き出す
モバイルエージェントの研究をしていてオブジェクトをファイルに書き出そうと考えました。かつてはシリアライズといえば、Serializableインタフェースによる方法が利用されていました。しかしこの方法だと、属性が追加されるなどした場合の互換性の問題がありました。
そこで、XMLEncoder/XMLDecoderによる方法です。J2SE 1.4から導入されました。これならSerializableインタフェースを実装しなくてもよく、Beansの規約に沿ってクラスを実装するだけ。結果はXMLとして書き出されるので、エディタでも閲覧変更可能。キタコレ。
使用例
(Idol.java)
import java.io.*;
public class Idol {
private String name;
private int age;
private double height;
private double weight;
private double bust;
private double waist;
private double hip;
public Idol() {}
public Idol(String name, int age, double height, double weight,
double bust, double waist, double hip) {
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
this.bust = bust;
this.waist = waist;
this.hip = hip;
}
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public void setAge(int age) { this.age = age; }
public int getAge() { return age; }
public void setHeight(double height) { this.height = height; }
public double getHeight() { return height; }
public void setWeight(double weight) { this.weight = weight; }
public double getWeight() { return weight; }
public void setBust(double bust) { this.bust = bust; }
public double getBust() { return bust; }
public void setWaist(double waist) { this.weight = weight; }
public double getWaist() { return waist; }
public void setHip(double hip) { this.hip = hip; }
public double getHip() { return hip; }
public String toString() {
return name + "です、えへ☆";
}
}
(XMLEncoderTest.java)
import java.beans.*;
import java.io.*;
public class XMLEncoderTest {
public static void main(String[] args) {
Idol haruka = new Idol("天海春香", 16, 158.0, 45.0, 83.0, 56.0, 80.0);
try {
XMLEncoder writer = new XMLEncoder(
new BufferedOutputStream(new FileOutputStream("haruka.xml")));
writer.writeObject(haruka);
writer.close();
} catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}
(XMLDecoderTest.java)
import java.beans.*;
import java.io.*;
public class XMLDecoderTest {
public static void main(String[] args) {
try {
XMLDecoder reader = new XMLDecoder(
new BufferedInputStream(new FileInputStream("haruka.xml")));
Idol haruka = (Idol)reader.readObject();
reader.close();
System.out.println(haruka);
} catch(FileNotFoundException e) {
e.printStackTrace();
}
}
}
実行例
・コンパイル $ javac -cp . *.java ・書き出し $ java -cp . XMLEncoderTest ・読み出し $ java -cp . XMLDecoderTest 天海春香です、えへ☆