Java Socket getOutputStream() method

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.

Syntax

Parameter

NA

Return

The getOutputStream() returns an output stream for writing bytes to this socket.

Throws

IOException- if an I/O error occurs when creating the output stream or if the socket is not connected.

Example 1

Test it Now

Output:

Output Stream: java.io.DataOutputStream@1540e19d

Example 2

Test it Now

Output:

Exception in thread "main" java.net.SocketException: Socket is closed
	at java.net.Socket.getOutputStream(Socket.java:943)
	at com.javaTpoint.JavaSocketGetOutputStreamExample2.main(JavaSocketGetOutputStreamExample2.java:22)

Example 3

Test it Now

Output:

Exception in thread "main" java.net.SocketException: Socket is not connected
	at java.net.Socket.getOutputStream(Socket.java:945)
	at com.javaTpoint.JavaSocketGetOutputStreamExample3.main(JavaSocketGetOutputStreamExample3.java:20)




Latest Courses