这是个简单的Demo……
/**
* 对象的序列化与反序列化
* ps:
* 1. 要序列化的对象必须实现Serialzalbe接口(……我竟然忘了)
* 2. 反序列化的is.readObject()方法读到文件末尾时,竟然抛出EOFException而非返回特殊值(-1,null之类),JDKAPI也表示这很坑爹。
* @author garview
*
* @Date 2013-11-4上午11:36:28
*/
public class SerializeDemo {
public static void main(String[] args) {
try {
File file = new File("c:/test.java");
ser(file, intiData());
reverseSer(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("未找到文件");
} catch (IOException e) {
e.printStackTrace();
System.out.println("写入对象失败");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} java
// 1.序列化对象(初始化对象、搭建传输管道,写对象,关闭管道资源)
public static void ser(File file, ArrayList<Book> books)
throws FileNotFoundException, IOException { .net
// 搭建传输管道
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream os = new ObjectOutputStream(fos);
// 写对象
for (Book temp : books) {
os.writeObject(temp);
} 对象
// 写入null,方便反序列化时判断结束
os.writeObject(null); 接口
os.close();
} three
// 1.反序列化对象(初始化对象、搭建传输管道,写对象,关闭管道资源)
public static void reverseSer(File src) throws FileNotFoundException,
IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(src);
ObjectInputStream is = new ObjectInputStream(fis); 资源
ArrayList<Book> books = new ArrayList<Book>(); get
Object temp = null;
while (true) {
//注意读到文件末尾会抛出EOFException
temp = is.readObject();
if (temp == null) {
break;
}
books.add((Book) temp);
} it
for (Book temp2 : books) {
System.out.println(temp2.toString());
}
is.close();
} io
public static ArrayList<Book> intiData() {
// 初始化对象
Book one = new Book("西游释厄传", 90, 55.0);
Book two = new Book("西游释厄传2", 90, 55.0);
Book three = new Book("西游释厄传3", 90, 55.0); class
ArrayList<Book> books = new ArrayList<Book>(); books.add(one); books.add(two); books.add(three); return books; }