📄 right4_8_2.htm
字号:
<html><head><title>JAVA编程语言</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><link rel="stylesheet" href="../../../css/text.css" type="text/css"></head><body bgcolor="#FFFFFF" text="#000000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" ><table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td valign="top"> <table width="92%" border="0" cellspacing="0" cellpadding="0" align="center" bgcolor="#FFFFFF"> <tr> <td valign="top"> <p class="pt9-black"> <span class="zhongdian">1. 定义一个可串行化对象<a name="01"></a></span><br> <br> public class Student implements Serializable{<br> int id; <font color="339900">//学号</font><br> String name; <font color="339900">//姓名</font><br> int age; <font color="339900">//年龄</font><br> String department <font color="339900">//系别</font><br> public Student(int id,String name,int age,String department){<br> this.id = id;<br> this.name = name;<br> this.age = age;<br> this.department = department;<br> }<br> }<br> <br> <span class="zhongdian">2. 构造对象的输入/输出流<a name="02"></a></span><br> <br> 要串行化一个对象,必须与一定的对象输入/输出流联系起来,通过对象输出流将对象状态保存下来,再通过对象输入流将对象状态恢复。<br> <br> java.io包中,提供了ObjectInputStream和ObjectOutputStream将数据流功能扩展至可读写对象。在ObjectInputStream中用readObject()方法可以直接读取一个对象,ObjectOutputStream中用writeObject()方法可以直接将对象保存到输出流中。<br> <br> Student stu=new Student(981036,"Liu Ming",18, "CSD");<br> FileOutputStream fo=new FileOutputStream("data.ser");<br> <font color="339900">//保存对象的状态</font><br> ObjectOutputStream so=new ObjectOutputStream(fo);<br> try{<br> so.writeObject(stu);<br> so.close();<br> }catch(IOException e )<br> {System.out.println(e);}<br> FileInputStream fi=new FileInputStream("data.ser");<br> ObjectInputStream si=new ObjectInputStream(fi);<br> <font color="339900">//恢复对象的状态</font><br> try{<br> stu=(Student)si.readObject();<br> si.close();<br> }catch(IOException e )<br> {System.out.println(e);}<br> <br> <font color="000099">在这个例子中,我们首先定义一个类Student,实现了 Serializable接口,然后通过对象输出流的writeObject()方法将Student对象保存到文件data.ser中。之后,通过对象输入流的readObject()方法从文件data.ser中读出保存下来的Student对象。 <br> </font> </p> </td> </tr> </table> </td> </tr></table></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -