Bootstrap

java串行化

1.先建立一个员工类
import java.io.Serializable;

public class Employee implements Serializable
{
int ID;
String Name;
transient float salary;
public Employee(int id,String name,float salary)
{
this.ID=id;
this.Name=name;
this.salary=salary;
}


}


2.在main方法中实现串行化

public static void main(String[] args) throws IOException,ClassNotFoundException
{
Employee em=new Employee(1,"cetus",5000);

try
{
FileOutputStream fo=new FileOutputStream("h:/data.ser");
ObjectOutputStream objs=new ObjectOutputStream(fo);
objs.writeObject(em);
objs.close();

}
catch(IOException e)
{
System.out.println(e);
}
em=null;
try
{
FileInputStream fis=new FileInputStream("h:/data.ser");
ObjectInputStream ois=new ObjectInputStream(fis);
em=(Employee)ois.readObject();
ois.close();
}
catch(IOException e)
{
System.out.println(e);
}

System.out.println("Employee Info:");

System.out.println("ID:" + em.ID);

System.out.println("Name:" + em.Name);

System.out.println("Saraly:" + em.salary);



}



summary:
1.用FileOutputStream 创建data.ser文件
2.用objectOutputstream 的writeobjecet(实例)写入数据
3.创建FileInputStream 读取data.ser文件
4.objectinputstream适配器似的读取FileInputStream,用readobject读取对象,要记得转换类型


ps:对于要保密的信息,可以用transient定义
;