您的位置:首页 > 编程语言 > Java开发

java编程心得(九)——序列化(Serializable)

2010-12-27 20:47 253 查看
今天解决了项目一个很重要的问题——序列化输出!现将我对Java序列化的理解与心得写下来:

一、序列化的代码:

1)首先是定义一个implements Serializable的类:

class A
implements Serializable{

}

2)然后是序列化的代码:

//将对象a写入文件file
A a = new A();
File file = new File(“文件路径”);
try
{
OutputStream outStream = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(outStream);
oos.writeObject(a);
oos.close();

}
catch (IOException e) {

//
TODO Auto-generated catch block

e.printStackTrace();
}

3)再是反序列化的代码:

//从文件file读出对象a

File file = new File(“文件路径”);

A a;
try
{
InputStream
inputStream = new FileInputStream(file);

ObjectInputStream ois = new ObjectInputStream(inputStream);
a = (A)ois.readObject();

}

catch(FileNotFoundException e)

{

System.out.println(e);

}

catch(IOException e)

{

System.out.println(e);

}

catch (ClassNotFoundException e)
{

e.printStackTrace();
}

二、序列化的设计思想与要注意的问题:

其不会序列化方法函数,只会序列化实例变量。简单地说就是将保存在内存中的各种对象的状态保存到数据库、文件等系统中。要注意的问题是:

①如果该类的某个属性标识为static类型的,则该属性不能序列化;

②如果该类的某个属性采用transient关键字标识,则该属性不能序列化;

③线程相关的属性不能序列化,要设置为transient来避免序列化;

④需要访问IO、本地资源、网络资源等属性同③;

⑤任何变量需要先初始化,例如:
public double[] d = null;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: