import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializableDemo {
/**
* 对象的序列化:就是指将对象从内存中存入到磁盘、数据库中等等
* 对象的反序列化:就是将对象从磁盘、数据库读到内存中
* @param args
*/
public static void main(String[] args) {
SerializableAttachment attachment = new SerializableAttachment("hello", 100);
SerializableDemo sd = new SerializableDemo();
sd.store(attachment, "F:\\1.txt");
SerializableAttachment sa = (SerializableAttachment) sd.getObject("F:\\1.txt");
System.out.println(sa);
}
//对象的序列化,存入磁盘的类必须实现了Serializable接口
public void store(Object obj, String path){
if (!(obj instanceof Serializable)) {
System.out.println(obj.getClass().getName() + " 这个类没有实现Serializable,不能被序列化");
return;
}
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(path));
oos.writeObject(obj);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (null != oos) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//对象的反序列化
public Object getObject(String path){
File src = new File(path);
Object obj = null;
if (!src.exists()) {
System.out.println(path + "不存在!");
}else {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(src));
obj = ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
if (null != ois) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return obj;
}
}
class SerializableAttachment implements Serializable{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public SerializableAttachment() {
super();
}
public SerializableAttachment(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "name:" + name + ", age" + age;
}
}
|