Serialize object with outputstream

2020-07-10 07:07发布

Suppose I have an OutputStream (and not an ObjectOutputStream). Is is possible to send a serialized object using the write method? Thanks!

4条回答
乱世女痞
2楼-- · 2020-07-10 07:46

You must have to use ObjectOutputStream class and its methods to *serialize* objects. In fact ObjectOutputStream is a sub-class of java.io.OutputStream (It is an abstract super class of byte-oriented streams). Take a look at an article on Java Serialization API.

EDIT: You can use XMLEncoder

(from the Doc : The XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean in the same way that the ObjectOutputStream can be used to create binary representation of Serializable objects)

查看更多
甜甜的少女心
3楼-- · 2020-07-10 07:52

You could use ObjectOutputStream to 'capture' the objects data in a byte Array and send this to the OutputStream.

String s = "test";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( s );
byte[] byteArray = baos.toByteArray();
for ( byte b : byteArray ) {
    System.out.print( (char) b );
}

Another non generic option would be to serialize the object in a string representation e.g. CSV

查看更多
欢心
4楼-- · 2020-07-10 08:06

Here is what you do to serialize the object:

new ObjectOutputStream(outputStream).writeObject(obj);

If you want to control the byte[] output:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(buffer);

oos.writeObject(obj);

oos.close();

byte[] rawData = buffer.toByteArray();
查看更多
狗以群分
5楼-- · 2020-07-10 08:11

This is trivial: you can simply wrap your original OutputStream in a new ObjectOutputStream, and then use the specialized methods of ObjectOutputStream:

OutputStream myOriginalOutputStream = ...;
ObjectOutputStream oos = new ObjectOutputStream(myOriginalOutputStream);
oos.writeObject(new MyObject());
oos.flush();
oos.close();

Internally, ObjectOutputStream will call the underlying OutputStream's write() method.

查看更多
登录 后发表回答