user10082400
user10082400

Reputation:

What differences are between ObjectInput/OutputStream and DataInput/OutputStream when applying to instances of primitive types?

It seems to me that both ObjectInputStream/ObjectOutputStream, and DataInputStream/DataOutputStream can apply to instances of primitive types. What differences between ObjectInputStream/ObjectOutputStream, and DataInputStream/DataOutputStream when they both apply to instances of primitive types?

Can they both (de)serialize instances of primitive types in the same way?

Upvotes: 1

Views: 46

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

Note: Don't use Java Serialization. Also DataOutputStream has some wacky formatting, so don't use that either.

DataOutputStream provides a layer over OutputStream that supports formatting data as required by Java class files. It doesn't add any tags/metadata, it just writes the data in a standard format. It's clearly part of an early compiler made public because it might be useful - typical of JDK1.00 classes.

ObjectOutputStream provides a layer over DataOutputStream (doesn't have to be implemented with that class, but the low-level data format is the same) that supports writing a specific file format containing arbitrary object data. As with most formats, this includes a bundle of headers.

When you write an object to an ObjectOutputStream, it'll also write the class description or a reference if it has been used since the last reset. The "data" methods are specified to format much the same as DataOutputStream, but the file already has a header. These methods are typically used in custom writeObject methods after defaultWriteObject or writeFields.

tl;dr There's a header with ObjectOutputStream; ObjectOutputStream is a (permeable) layer over DataOutputStream.

Upvotes: 0

Konrad Neitzel
Konrad Neitzel

Reputation: 760

That is something that you can easily find out yourself with a quick test:

import java.io.*;

public class Test {
    public static void main(String[] args) {
        try {
            ObjectOutputStream out1 = new ObjectOutputStream(new FileOutputStream("1.out"));
            out1.writeByte(100);
            out1.close();

            DataOutputStream out2 = new DataOutputStream(new FileOutputStream("2.out"));
            out2.writeByte(100);
            out2.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

When you run this code, then you will directly see the difference: The file of the ObjectOutputStream is bigger. ObjectOutputStream writes a total of 7 bytes instead of just one Byte which the DataOutputStream is writing.

The ObjectOutputStream is not just writing the core data. It is using the Java Object Serialization Stream Protocol which can be found at https://docs.oracle.com/javase/7/docs/platform/serialization/spec/protocol.html#10258

Upvotes: 1

Related Questions