请教java.io.Serializable的说明,我要的详细的例子和说明

shuki 2003-08-21 08:40:22
各位大哥,
我不太了解java.io.Serializable这个类,所以请求详细说明。

不要光给个网址,否则不给分
...全文
30 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
林中漫步1982 2003-08-22
  • 打赏
  • 举报
回复
接口java.io.Serializable 用来对对象进行序列化,假若某个对象要在网络上传输
或者要把对象写入文件或从文件读出,那么这个对象就必须实现java.io.Serializable。
接口java.io.Serializable只是个标志性接口,里面无任何方法。
下面的例子中, 类Friend 若不实现java.io.Serializable ,运行必会出错。

import java.io.*;
public class Test
{
public static void main( String args[] )
{
Friend friend=new Friend("firstname","lastname");

File file=new File("e:\\a.dat");

try{
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream( file ));
output.writeObject(friend); //把对象写入文件
output.flush();
output.close();
}
catch(FileNotFoundException e)
{}
catch(IOException e)
{
e.printStackTrace();
}

try{
ObjectInputStream input=new ObjectInputStream(
new FileInputStream(file));
Friend f=(Friend)input.readObject();//从文件读对象
System.out.println(f.toString()); //验证操作
}
catch(ClassNotFoundException e)
{}
catch(FileNotFoundException e)
{}
catch(IOException e)
{
e.printStackTrace();
}
}
}

class Friend implements Serializable{
private String firstName;
private String lastName;

public Friend(String first,String last)
{
firstName=first;
lastName=last;
}
public String toString()
{
return (firstName+", "+lastName);
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧