使用Java中的Streams进行序列化

时间:2011-05-28 03:50:47

标签: java c++ serialization stream

在C ++中,我创建了一个名为Serializer的类。我想在Java中复制功能。以下是Serializer的工作原理。

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(); }
  • 是否有任何内置类可以自由地操作字节数据?
  • 如果没有,您可以一起使用输入和输出流吗?
  • 如果不能,您如何在InputStream和OutputStream之间进行转换?
  • 有没有其他方法可以解决这个问题?

侧注:所有字节数据都可以在内存中。记忆不是问题。

谢谢。

1 个答案:

答案 0 :(得分:4)

Java有一个object serialisation system,听起来非常适合你想做的事情。快速摘要:

  • 让您的班级实施java.io.Serializable,并添加private static final long serialVersionUID字段(使用您喜欢的任何值 - 通常我只是从1开始)。
  • 将您想要序列化的所有字段标记为transient;所有非transient字段都将被序列化。
  • 确保您要序列化的所有字段都是原始字段或也是可序列化类型---所有非可序列化类型都必须是瞬态的。
  • 每当您对序列化的字段进行更改时,请更改serialVersionUID。通常我只是将值提高1。
  • 对于自定义序列化,您可以实施readObjectwriteObject方法。
  • 对于认真的自定义序列化,还有java.io.Externalizable

要实际序列化或反序列化对象,请使用DataOutputStreamDataInputStream类。是的,您可以使用压缩和/或加密来包装流。 : - )