论坛首页 Java企业应用论坛

序列化(一)

浏览 1614 次
锁定老帖子 主题:序列化(一)
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-02-10   最后修改:2009-02-14
OO
模型类:
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();
		}
	}
}

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics