JAvaシーケンス化とObjectOutputStreamとObjectInputStream

1938 ワード

詳細
テストのエンティティークラス:
public class Param implements Serializable {

	private static final long serialVersionUID = 5187074869820982336L;
	
	
	private Integer param1;
	private String param2;

	public Integer getParam1() {
		return param1;
	}

	public void setParam1(Integer param1) {
		this.param1 = param1;
	}

	public String getParam2() {
		return param2;
	}

	public void setParam2(String param2) {
		this.param2 = param2;
	}

}

テスト:
public class Main {

	public static void main(String[] args) throws Exception {
		SerializeParam();
		
		Param param = DeserializeParam();
		System.out.println(MessageFormat.format("param1={0},param2={1}", param.getParam1(), param.getParam2()));
	}

	/**
	 *  
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private static void SerializeParam() throws FileNotFoundException, IOException {
		Param param = new Param();
		param.setParam1(123);
		param.setParam2("asdf");
		
		ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream( new File("E:/param.txt") ));
		oo.writeObject(param);
		System.out.println("Person !");
		oo.close();
	}
	
	/**
	 *  
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	private static Param DeserializeParam() throws Exception, IOException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream( new File("E:/param.txt")));
        Param param = (Param) ois.readObject();
        System.out.println("Person !");
        ois.close();
        return param;
    }

}