Java sockets: DataOutputStream or OutputStream?

David picture David · Aug 8, 2011 · Viewed 15.1k times · Source

I'm still relatively new to sockets, and I haven't seen any information regarding this subject.

To write to a connected socket, you can either use

socket.getOutputStream().write

Or create a new DataOutputStream from the socket OutputStream and write to that.

  • What is considered "good practice", using a DataOutputStream or OutputStream? Most of the examples I find on the internet use DataOutputStream (to send Strings, such as in a two way chat).
  • Are there any advantages or disadvantages from using DataOutputStream over OutputStream?
  • Is there any difference in performance that is noticeable between these two when, for example, sending files?

Answer

Jérôme Verstrynge picture Jérôme Verstrynge · Aug 8, 2011

DataOutputStream makes sure the data is formatted in a platform independent way. This is the big benefit. It makes sure the party on the other side will be able to read it. There is no significant performance difference between both.

You should use OutputStream only if you transfer raw binary data.