objectstream.java

来自「这是清华大学编写的JAVA教材中所有题目的源代码!」· Java 代码 · 共 61 行

JAVA
61
字号
import java.io.*;

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;
	}
}


class ObjectStream
{
	public static void main(String args[]) throws IOException,ClassNotFoundException
	{
		Student stu=new Student(981036,"john",18,"Computer");
		FileOutputStream fos=new FileOutputStream("stu.txt");
		ObjectOutputStream oos=new ObjectOutputStream(fos);
		
		try
		{
		   oos.writeObject(stu); 
		   oos.close();
		}
		catch(IOException e )
		{
			System.out.println(e);
		}
		
		Object stu1=null;
		FileInputStream fis=new FileInputStream("stu.txt");
		ObjectInputStream ois=new ObjectInputStream(fis);
		
		try
		{
			//stu=(Student)ois.readObject();
			stu1=ois.readObject();
			ois.close();
		}
		catch(IOException e )
		{
			System.out.println(e);
		}
		/*
		System.out.println("ID is:"+stu.id);
		System.out.println("name is:"+stu.name);
		System.out.println("age is:"+stu.age);
		System.out.println("department is:"+stu.department+"\n");
		*/
		System.out.println(stu1);
	}
}

⌨️ 快捷键说明

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