Java序列化(2)
程序员文章站
2022-02-19 06:34:54
...
在前面刚转载了一篇文章,我觉得理论讲的还不错,但是例子不够完整,所以我就在帖一个完整点的例子.
如:
package com.exam.jpart;
import java.io.Serializable;
/**
*
* @author zyong
* 这是一个简单的JavaBean类,就序列化该类
*/
@SuppressWarnings("serial")
public class User implements Serializable {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.exam.jpart;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
*
* @author zyong
* 这是把对象信息保存到物理内存中,和读取出来
*/
public class SerializableDemo {
/**
*
* @param obj
* 为一个需要序列化的对象
* @param file
* 路径
* @throws IOException
*/
public void writeObject(Object obj, String file) throws IOException {
FileOutputStream fileOutput = new FileOutputStream(file);
ObjectOutputStream objOutput = new ObjectOutputStream(fileOutput);
objOutput.writeObject(obj);
objOutput.close();
fileOutput.close();
}
/**
*
* @param file
* 路径
* @return 一个对象
* @throws IOException
* @throws ClassNotFoundException
*/
public Object readObject(String file) throws IOException,
ClassNotFoundException {
FileInputStream fileInput = new FileInputStream(file);
ObjectInputStream objInput = new ObjectInputStream(fileInput);
Object obj = objInput.readObject();
return obj;
}
/**
* @param args
*/
public static void main(String[] args) {
SerializableDemo demo = new SerializableDemo();
User user = new User();
user.setId(1);
user.setName("风中叶'");
user.setAge(22);
String file="user.obj";
try {
/*
* 输出对象
*/
demo.writeObject(user, file);
/*
* 读取对象
*
*/
User user2=(User)demo.readObject(file);
System.out.println("user.name="+user2.getName());
System.out.println("user.age="+user2.getAge());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}