Javaシーケンス化(2)

3216 ワード

前に1篇の文章を転載したばかりで、私は理論の言うのは悪くないと思って、しかし例は完全ではありませんて、だから私は1つの完全な点の例を投稿します.
次のようになります.
package com.exam.jpart;

import java.io.Serializable;
/**
 * 
 * @author zyong
 *        JavaBean ,      
 */
@SuppressWarnings("serial")
public class User implements Serializable {
	
	private Integer id;
	
	private String name;
	
	private Integer age;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}
	
	
	
}

 
package com.exam.jpart;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * 
 * @author zyong
 *                ,     
 */
public class SerializableDemo {

	/**
	 * 
	 * @param obj
	 *                       
	 * @param file
	 *              
	 * @throws IOException
	 */
	public void writeObject(Object obj, String file) throws IOException {
		FileOutputStream fileOutput = new FileOutputStream(file);
		ObjectOutputStream objOutput = new ObjectOutputStream(fileOutput);
		objOutput.writeObject(obj);
		objOutput.close();
		fileOutput.close();
	}

	/**
	 * 
	 * @param file
	 *              
	 * @return     
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public Object readObject(String file) throws IOException,
			ClassNotFoundException {
		FileInputStream fileInput = new FileInputStream(file);
		ObjectInputStream objInput = new ObjectInputStream(fileInput);
		Object obj = objInput.readObject();
		return obj;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		SerializableDemo demo = new SerializableDemo();
		
		User user = new User();
		user.setId(1);
		user.setName("   '");
		user.setAge(22);
		
		String file="user.obj";
		
		try {
			/*
			 *     
			 */
			demo.writeObject(user, file);
			/*
			 *     
			 * 
			 */
			User user2=(User)demo.readObject(file);
			
			System.out.println("user.name="+user2.getName());
			System.out.println("user.age="+user2.getAge());
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.getMessage());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}