Java.io.Serializable

接口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);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值