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
*/
[java][io][Serialize]对象序列化
最新推荐文章于 2024-05-22 15:02:39 发布