java编程心得(九)——序列化(Serializable)
2010-12-27 20:47
316 查看
今天解决了项目一个很重要的问题——序列化输出!现将我对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;
一、序列化的代码:
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;
相关文章推荐
- 我对Java Serializable(序列化)的理解和总结
- java序列化Serializable
- 对Java Serializable(序列化)的理解和总结
- java序列化(Serializable)的作用和反序列化
- 我对Java Serializable(序列化)的理解和总结
- java序列化Serializable 学习入门
- Java学习心得之GUI编程(一)
- Java 序列化Serializable详解
- Java Serializable(序列化)的理解和总结
- 什么是java序列化,如何实现java序列化?或者请解释Serializable接口的作用
- JAVA 对象序列化(一)——Serializable
- Netty 快速入门系列 - Chapter 5 Netty之序列化【第十二讲】 Java Serializable
- java 序列化.Serializable
- java序列化接口Serializable的使用
- JAVA 对象序列化——Serializable(转)
- java序列化(Serializable)的作用和反序列化
- Java 序列化 Serializable
- Java序列化Serializable
- 对Java Serializable(序列化)的理解和总结
- 我对Java Serializable(序列化)的理解和总结