17

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?
David
  • 15,652
  • 26
  • 115
  • 156

3 Answers3

11

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.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
  • So what would you suggest if you want to create a platform-independent java application that can send files? – David Aug 08 '11 at 15:10
  • Even if the files only contain raw bytes, you can still send them with DataOutputStream, so I would go for DataOuputStream in all cases. – Jérôme Verstrynge Aug 08 '11 at 15:21
  • `DataOutputStream` only 'makes sure the data is formatted in a platform-independent way` if you use the extra APIs it provides. Its `write()` methods do not have magical properties. If you're only using those, (a) there is no performance difference at all, and (b) there is no point in using `DataOutputStream` at all. If you're using the extra APIs there is nothing to compare its performance with. So the statement about performance differences is basically meaningless. – user207421 Feb 24 '17 at 00:15
2

Use DataOutputStream if you need the extra APIs. If you don't, there is no point. But you should always wrap the socket's output stream in a BufferedOutputStream if you are doing small writes, and flush() when appropriate, i.e. before you read the socket for example.

user207421
  • 305,947
  • 44
  • 307
  • 483
-1

Just now I came to know a difference between dataoutputstream and outputstreamwriter while working with a SOAP services... I tried to pass arabic data through request XML but in the response XML I'm getting some junk characters in place of arabic data then I tried to encode (UTF-8) the request but there is no such method to encode in DataOutputStream where as you can encode the request in OutputStreamWriter before sending the request. OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); out.write(inputXML);