浏览 1608 次
锁定老帖子 主题:序列化(一)
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-02-10
最后修改:2009-02-14
package com.wlh; import java.io.Serializable; public class Worker implements Serializable { private String name; private String sex; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } 序列化&反序列化 测试类: package com.wlh; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import com.wlh.Worker; import junit.framework.TestCase; public class ObjectSerializableTest extends TestCase { private static String fileName="./worker.dat"; /** * 序列化 */ public void testSerializable1(){ Worker worker=new Worker(); worker.setAge(26); worker.setName("wlh"); worker.setSex("man"); try { File file=new File(fileName); if(!file.exists()){ file.createNewFile(); } FileOutputStream fos=new FileOutputStream(file); ObjectOutputStream oops=new ObjectOutputStream(fos); oops.writeObject(worker);//序列化方法writeObject() } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 反序列化 */ public void TestUnSerializable(){ try { FileInputStream fis=new FileInputStream(fileName); ObjectInputStream ois=new ObjectInputStream(fis); Worker newWoker=(Worker) ois.readObject(); System.out.println("age="+newWoker.getAge()); System.out.println("name="+newWoker.getName()); System.out.println("sex="+newWoker.getSex()); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |