Java序列化

    前段时间用java做socket传输数据,由于java只支持字节流,所以要将数据转换成bytes数组,用到了序列化的知识,下面是测试代码。

TestDataClass.java

import java.io.Serializable;


public class TestDataClass implements Serializable {
	public float x;
	public float y;
	public int type;
	public float z;
}


JavaTestSerialData.java

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


public class JavaTestSerialData {

	/**
	 * @param args
	 * @throws ClassNotFoundException 
	 */
	public static void main(String[] args) throws ClassNotFoundException {
		// TODO Auto-generated method stub
		TestDataClass data=new TestDataClass();
		data.x=110.1f;
		data.y=112.3f;
		data.type=1;
		data.z=50.60f;

		//序列化对象
		try {
			ByteArrayOutputStream bos=new ByteArrayOutputStream();
			ObjectOutputStream oos=new ObjectOutputStream(bos);
			oos.writeObject(data);
			oos.flush();
			
			byte[] bytedata=bos.toByteArray();
			System.out.println("after serial the data lenght is "+bytedata.length+" bytes.");
			oos.close();
			bos.close();
			
			//unserial
			ByteArrayInputStream bis=new ByteArrayInputStream(bytedata);
			ObjectInputStream ois=new ObjectInputStream(bis);
			TestDataClass newData=(TestDataClass)ois.readObject();
			ois.close();
			bis.close();
			
			System.out.println("x is "+newData.x+"    y is "+newData.y +" type="+newData.type+" z="+newData.z);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}


 

你可能感兴趣的:(Java序列化)