difference between “DataOutputStream” and “ObjectO

2020-06-28 16:03发布

I'm a beginner programmer following this Java Tutorial.

In the Basic I/O section, two of the classes mentioned are Data Streams and Object Streams.

They are used very similarily:

out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));

// ..

in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));

for DataInputStream and

out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));

// ..

in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dataFile)));

for ObjectInputStream

I know it says that DataInputStreams are used for primitive objects, and ObjectInputStreams are used for objects (and serialization of them), so which one should I use? It isn't a noticeable difference between the two example classes which both use primitive types. I usually use primitive types, too.

For performance, which one is better? and are there any other large differences?

thanks.

标签: java io
1条回答
Emotional °昔
2楼-- · 2020-06-28 16:40

DataStreams are used for I/O of primitive types which are int, float, double and so on.

ObjectStreams are used for I/O of objects.

If you know you're going to be explicitly working with primitive types then use DataStreams, otherwise go with the more generic ObjectStreams which implement the DataInput interface as well as ObjectInput interface so can work with primitives as well as objects.

查看更多
登录 后发表回答