Geek-Side

Resource > Serialize
Serialize -> DeSerializeのサンプル。

Serialize処理とSerialize対象のクラスHoge。
package sample;

 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.ObjectOutput;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.util.Arrays;
 import java.util.Date;
 import java.util.List;

 public class SerializeSample {
 	public static void main(String[] args) throws IOException, ClassNotFoundException {
 		FileOutputStream file = new FileOutputStream("C:\hoge");
 		ObjectOutput out = new ObjectOutputStream(file);
		
 		Hoge hoge = new Hoge("hoge");
 		Hoge fuga = new Hoge("fuga");
 		List<Hoge> list =	Arrays.asList(hoge, fuga);

 		out.writeObject(new Date());
 		out.writeObject(list);

 		out.flush();
 		out.close();
 		file.close();

 		System.out.println("write!");
		
 		DeSerializeSample.main(new String[] {""});
 	}
 	static class Hoge implements Serializable {
 		/**	default UID */
 		private static final long serialVersionUID = 1L;
 		String hoge;
 		public Hoge(String hoge) {
 			this.hoge = hoge;
 		}
 		public String getHoge() {
 			return hoge;
 		}
 	}
 }
Deserialize処理
 package sample;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectInputStream;
 import java.util.Date;
 import java.util.List;

 import sample.SerializeSample.Hoge;

 public class DeSerializeSample {
 	/**
 	 * @param args
 	 * @throws IOException
 	 * @throws ClassNotFoundException
 	 */
 	public static void main(String[] args) throws IOException, ClassNotFoundException {
 		FileInputStream file = new FileInputStream("C:\hoge");
 		ObjectInput input = new ObjectInputStream(file);

 		Date date = (Date) input.readObject();
 		List<Hoge> list = (List) input.readObject();
 		input.close();

 		file.close();
 		System.out.println(date);
		
 		for(Hoge bean : list) {
 			System.out.println(bean.getHoge());
 		}
 	}
 }