序列化和反序列化

         在进行数据处理过程中,通常可能存在多个步骤,每个步骤都会产生一种新的中间数据格式,通常我们会将这些中间数据序列化后保存至缓存文件中,在后续步骤中再反序列化之拿来使用,这样使得数据的处理更加有层次感.

         1.c++中的序列化和反序列化

            通常我们都采用重载CObject类的Serialize方法结合CArchive类来实现.

            1)创建一个Test类:

            Test.h:

class CTest :
	public CObject
{
public:
	CTest(void);
	DECLARE_SERIAL(CTest)	
	CTest(int a,double b);
	~CTest(void);
	void Serialize(CArchive& ar);
private:
	int m_nNum;
	double m_dNum;
};
             Test.cpp:

            

#include "Test.h"
IMPLEMENT_SERIAL(CTest, CObject, 1)
CTest::CTest(void):m_nNum(100),m_dNum(1000.2)
{
}

CTest::CTest(int a,double b):m_nNum(a),m_dNum(b)
{
}

CTest::~CTest(void)
{
}

void CTest::Serialize(CArchive &ar)
{
	if(ar.IsStoring())
	{
		ar << m_dNum;
		ar << m_nNum;
	}
	else
	{
		ar >> m_dNum;
		ar >> m_nNum;		
	}
}
           
           2)序列化和反序列化 
CTest* pTest = new CTest(1000,2000);
	CFile fe;
	//写出
	if(fe.Open(_T("D:\\rrrr.txt"),CFile::typeBinary | CFile::modeWrite))
	{
		CArchive ar(&fe,CArchive::store);
		ar<<pTest;
	}	
	fe.Close();
	//读入
	if(fe.Open(_T("D:\\rrrr.txt"),CFile::typeBinary | CFile::modeRead))
	{
		CArchive ar(&fe,CArchive::load);
		CTest *pNewTest = NULL;
		ar>>pNewTest;
	}	

          2.Java中的序列化和反序列化

              序列化的类必须实现Serializable接口,通过ObjectOutputStream和ObjectInputStream实现写出和读入.

              1)类的创建:

public class testSerial implements Serializable{
	static final long serialVersionUID = 1L;//序列化时为了保持版本的兼容性,即在版本升级时反序列化仍保持对象的唯一性
	public int a = 100;
	public double b = 100.20;
}

              2)序列化和反序列化:

//写入
		FileOutputStream fs = new FileOutputStream("D:\\testt.txt");
		ObjectOutputStream os = new ObjectOutputStream(fs);
		os.writeObject(ts);
		os.close();
		//读取	
		FileInputStream fsIn = new FileInputStream("D:\\testt.txt");
		ObjectInputStream osIn = new ObjectInputStream(fsIn);
		testSerial ts1 = (testSerial)osIn.readObject();
		osIn.close();


你可能感兴趣的:(java,C++,序列化)