接口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);
}
}
或者要把对象写入文件或从文件读出,那么这个对象就必须实现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);
}
}