objectser.java

来自「java的书上例子」· Java 代码 · 共 70 行

JAVA
70
字号
import java.io.*;
//Student类实现Serializable接口
class Student implements Serializable
{
	int id;
	String name;
	int age;
	String department;
	public Student(int id,String name,int age,String department)
	{
		this.id=id;
		this.name=name;
		this.age=age;
		this.department=department;
	}
	//一般可不重写,定制串行化时需要重写writeObject()方法
	private void writeObject(ObjectOutputStream out)throws IOException
	{
		out.writeInt(id);
		out.writeInt(age);
		out.writeUTF(name);
		out.writeUTF(department);
	}
	//一般可不重写,定制串行化时需要重写readObject()方法
	private void readObject(ObjectInputStream in)throws IOException
	{
		id=in.readInt();
		age=in.readInt();
		name=in.readUTF();
		department=in.readUTF();
	}
}

public class Objectser
{
	public static void main(String args[]) throws IOException,ClassNotFoundException
	{ // stu对象与ObjectOutputStream联系起来
		Student stu=new Student(20001001,"LiuMing",20,"CSD");
		FileOutputStream fout=new FileOutputStream("data.ser");
		ObjectOutputStream sout=new ObjectOutputStream(fout);
		try
		{
			sout.writeObject(stu);  //输出流将对象状态存入文件"data.ser"
			sout.close();
		}
		catch(IOException e)
		{
			System.out.println(e);
		}
		stu=null;
		// stu对象与ObjectInputStream联系起来
		FileInputStream fin=new FileInputStream("data.ser");
		ObjectInputStream sin=new ObjectInputStream(fin);
		try
		{
			stu=(Student)sin.readObject();  //输入流将对象状态从文件"data.ser"读出
			sin.close();
		}
		catch(IOException e)
		{
			System.out.println(e);
		}
		System.out.println("Student info:");
		System.out.println("ID  : "+stu.id);
		System.out.println("Name: "+stu.name);
		System.out.println("Age : "+stu.age);
		System.out.println("Dep.: "+stu.department);
	}
}

⌨️ 快捷键说明

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