【Java】Serializableの基本使い方(オブジェクトをファイルに保存)

Javaコード:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class CtjSeria implements Serializable {

private static final long serialVersionUID = -3450064362986273896L;

private int width;
private int height;

public int getWidth() {
return width;
}

public void setWidth(int width) {
this.width = width;
}

public int getHeight() {
return height;
}

public void setHeight(int height) {
this.height = height;
}

public static void main(String[] args) {
CtjSeria tmdSer = new CtjSeria();
tmdSer.setHeight(30);
tmdSer.setWidth(100);
try {
FileOutputStream fs = new FileOutputStream(“D:\\foo.ser");
ObjectOutputStream ots = new ObjectOutputStream(fs);
ots.writeObject(tmdSer);
ots.close();

FileInputStream fit = new FileInputStream(“D:\\foo.ser");
ObjectInputStream ois = new ObjectInputStream(fit);
CtjSeria cta = (CtjSeria) ois.readObject();
ois.close();
System.out.println(cta.height + “," + cta.width);
} catch (Exception e) {
e.printStackTrace();
}

}

}

Java

Posted by arkgame