java对序列化提供了非常方便的支持,在定义类的时候,如果想让对象可以被序列化,必须实现 implements serializable
比如,对已存在的wang.txt进行序列化,得到的字节输出到wang1.txt文件中
package serializable;
/*
* 文本文件的序列化
*/
import java.io.*;
public class test implements serializable
{
public static void main(string[] args) throws classnotfoundexception
{
file file=new file("d:\\wang.txt");
file fi = new file("d:\\wang1.txt");
try
{
file.createnewfile();
}
catch(ioexception e)
{
e.printstacktrace();
}
try
{
//序列化
fileoutputstream fos = new fileoutputstream(fi);
objectoutputstream oos = new objectoutputstream(fos);
oos.writeobject(file);
oos.flush();
oos.close();
fos.close();
//反序列化
fileinputstream fis = new fileinputstream(fi);
objectinputstream ois = new objectinputstream(fis);
file file1= (file) ois.readobject(); //反序列化一个对象
}
catch (ioexception e)
{
e.printstacktrace();
}
}
}