[java][io][serialize] 객체 서열화

1693 단어 javajvm



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
 * 
 *  .
 *  .
 *  JVM class , ClassNotFoundException
 *
 */
public class SerialDemo {

	public static void main(String[] args) throws Exception {
		final String file = "d:\\demo.txt";
		Demo demo = new Demo(5);
		serialize(demo, file);
		deserialize(file);

	}
	// 
	static void serialize(Object obj, String filePath) throws Exception{
		FileOutputStream file = new FileOutputStream(filePath);
		ObjectOutputStream out = new ObjectOutputStream(file);
		out.writeObject(obj);
		out.close();
		System.out.println("serialize end.");
	}
	// 
	static void deserialize(String filePath) throws Exception{
		FileInputStream file = new FileInputStream(filePath);
		ObjectInputStream in = new ObjectInputStream(file);
		Object obj = in.readObject();
		in.close();
		System.out.println(obj.toString());
	}
	
	static class Demo implements Serializable{

		private static final long serialVersionUID = -3161633102764071778L;
		
		private int count;
		
		public Demo(int n){
			System.out.println("demo construct(n)");
			count = n;
		}
		
		public String toString(){
			return Integer.toString(count);
		}
	}

}

/*
demo construct(n)
serialize end.
5
*/

좋은 웹페이지 즐겨찾기