如何解决Java中使用流进行序列化
| 在C ++中,我创建了一个名为Serializer的类。我想复制Java中的功能。这是序列化器的工作方式。Serializer s;
s.writeString(myString); // automatically converted to Big-Endian unicode string with length prepended.
s.writeInt(myInt); // automatically converted to Big-Endian integer (swizzled if necessary)
s.writeObject(myObject); // which implements the Serializable interface
{
s.writeInt(myObjectId); // internally,it writes the data that I want to serialize.
...
}
ZlibCompressor.compress(s); // \'s\' is compressed
{
bytes = s.getBytes(); // internally,it gets bytes,...
compressFunc(bytes); // compress them
s.overwrite(bytes); // and overwrites
}
AESCipher.encrypt(s); // similarly,\'s\' is encrypted
// and the reverse in the same file,using the same all-in-one class to manipulate byte data.
AESCipher.decrypt(s);
ZlibCompressor.decompress(s);
s.readString(myString);
s.readInt(myInt);
s.readObject(myObject);
当然,这些是您可以执行的其他一些功能(从C ++复制和粘贴):
ByteArray Split(const Uint32& start,const Uint32& size);
inline Uint32 GetSize() const { return mBytes.size(); }
inline const Uint32& GetPos() const { return mPos; }
inline Bool IsEmpty() const { return mBytes.empty(); }
inline const Bool& IsError() const { return mError; }
inline void Resize(const Uint32& size,const Byte& val = 0) { mBytes.resize(size,val); }
inline void SetPos(const Uint32& pos) const { mPos = pos; }
inline void Reset() const { mPos = 0; mError = false; }
inline void Clear() { mBytes.clear(); Reset(); }
inline void Push(const Byte& x) { mBytes.push_back(x); }
inline void Pop() { mBytes.pop_back(); }
是否有任何内置的类可以自由操作字节数据呢?
如果没有,可以一起使用Input和Output流吗?
如果不能,如何在InputStream和OutputStream之间转换?
还有其他解决此问题的方法吗?
注意:所有字节数据都可以在内存中。内存不是问题。
谢谢。
解决方法
Java有一个对象序列化系统,听起来很适合您想做的事情。快速总结:
让您的类实现
java.io.Serializable
,并添加private static final long serialVersionUID
字段(使用您喜欢的任何值-通常我只从1开始)。
将您不想序列化的所有字段标记为transient
;所有非4字段将被序列化。
确保要序列化的所有字段要么都是原始字段,要么都是可序列化的类型-所有不可序列化的类型都必须是瞬态的。
每当您对要序列化的字段进行更改时,请更改ѭ6。通常我只将值增加1。
对于自定义序列化,可以实现readObject
和writeObject
方法。
对于认真的自定义序列化,还有java.io.Externalizable
。
要实际序列化或反序列化对象,请使用DataOutputStream
和DataInputStream
类。是的,您可以使用压缩和/或加密包装流。 :-)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。