转载链接:http://jingbo2759.blog.163.com/blog/static/98375315200972943020873/
Serializable这个是标记性的接口...标记性就是说,这个接口没有提供任何的方法.所以我们也不需要实现方法.但是如果某一个类需要被序列化,那么,他就必须实现这个接口...
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ObjectStreamTest
{
public static void main(String[] args)
{
T t = new T();
t.k = 15;
try
{
FileOutputStream fos = new FileOutputStream("333.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(t);
fos.close();
oos.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
try
{
FileInputStream fis = new FileInputStream("333.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
T t2 = (T)ois.readObject();
System.out.println(t2.i);
System.out.println(t2.k);
System.out.println(t2.s);
System.out.println(t2.j);
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
class T implements Serializable
{
int i = 20;
short j = 10;
String s = "hello";
int k = 100;
/*一般可不用重写,定制串行化时需要重写 这两个方法,
这两个方法应该同时对应出现
private void writeObject(ObjectOutputStream out) throws IOException
{}
private void readObject(ObjectInputStream in) throws IOException
{}
*/
}