java DataOutputStream getOutputStream() getInputStream()

6.6k Views Asked by At

one question

in the case for example of

DataOutputStream output= new DataOutputStream(clientSocket.getOutputStream()) ;

or

DataInputStream in = new   DataInputStream(clientSocket.getInputStream());

must these objects to be created each time i need an I/O operation or just invoke a read or a write on them each time i need??? ( plus some flushing after each operaration)

2

There are 2 best solutions below

0
On BEST ANSWER

You must create these objects only once, that is, after your socket has been initialized.

0
On

Both variants are possible, but it is more useful to create them only once.

If you want some buffering (to avoid sending a new TCP packet for each write command), you may want to think about putting a BufferedInputStream between the Socket and DataIn/Output:

DataOutput output = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
DataInput input   = new DataInputStream (new BufferedInputStream (clientSocket.getInputStream()));

I'm using the interfaces DataInput/DataOutput instead of the Stream classes here, since often you'll only need the methods defined there.