Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java sockets: DataOutputStream or OutputStream?

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?
like image 545
David Avatar asked Aug 08 '11 15:08

David


People also ask

When should I use Dataoutputstream?

A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

How is a socket InputStream and OutputStream created in Java?

In Java, to send data via the socket, you get an OutputStream (1) from it, and write to the OutputStream (you output some data). To read data from the socket, you get its InputStream , and read input from this second stream. You can think of the streams as a pair of one-way pipes connected to a socket on the wall.

What is DataInputStream and Dataoutputstream in Java?

public class DataInputStream extends FilterInputStream implements DataInput. A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.

What is the use of getOutputStream in Java?

The getOutputStream() method of Java Socket class returns an output stream for the given socket. If you close the returned OutputStream then it will close the linked socket.


1 Answers

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.

like image 128
Jérôme Verstrynge Avatar answered Nov 09 '22 07:11

Jérôme Verstrynge