您的位置:首页 > 其它

对象序列化

2014-06-08 19:18 375 查看
对象序列化

1:首先该对象要实现Serializable的接口

public class Person implements Serializable{

private static final long serialVersionUID = 1L;
private String name;

public String getName() {
return name;
}

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

}


2:将对象序列化到一个文件中(当然你也可以序列化到其他地方)

public class PersonTest {

public static void main(String[] args) {
Person p = new Person();
p.setName("张三");//为了测试有更直接的效果

ObjectOutputStream oos = null;//为什么要采用这个流,因为我们要对对象进行直接的操作
try {
oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));
oos.writeObject(p);//这里是对对象的直接操作
} catch (IOException e) {
e.printStackTrace();
} finally{
if(oos!=null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}


3:从文件中将对象取出

public class PersonTest2 {

public static void main(String[] args) {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("oos.txt"));
Person p = (Person) ois.readObject();
System.out.println(p.getName());//从这可看到对象对象序列化后取出的效果
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ois!=null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  对象序列化