serializationdemo.java

来自「国外的数据结构与算法分析用书」· Java 代码 · 共 40 行

JAVA
40
字号
import java.io.*;

public class SerializationDemo
{
	public static void main(String[] args)
	{
		/*	Serialize a student object. */
		try
		{
			Student s1 = new Student("Tim Short", "Computer Science", 2);
			System.out.println("s1: " + s1);

			FileOutputStream fos = new FileOutputStream("student.dat");
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(s1);
			oos.flush();
			oos.close();
		} catch (Exception e)
		{
			System.err.println("Serialization exception");
			e.printStackTrace();
			throw new Error("Serialization exception");
		}

		/*	Deserialize a student object. */
		try
		{
			Student s2;
			FileInputStream fis = new FileInputStream("student.dat");
			ObjectInputStream ois = new ObjectInputStream(fis);
			s2 = (Student) ois.readObject();
			ois.close();
			System.out.println("s2: " + s2);
		} catch (Exception e)
		{
			System.err.println("Deserialization exception: " + e);
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?