Re: getOutputStream() and getInputStream()
From: John C. Bollinger (jobollin_at_indiana.edu)
Date: Mon, 01 Dec 2003 12:25:33 -0500
> I'm trying to understand somebody's code. I've listed some lines
> The documents on internet still let me confused about what
> "getOutputStream()" and "getInputStream()" are doing?
They don't mean anything outside the context of an object on which they
are invoked. One would guess that the first probably returns an
OutputStream, whereas the second probably returns an InputStream, but
the significance of those streams is impossible to judge.
You aren't very clear about which documents you have been looking at on
the Internet. Do you mean the Java API documentation? If not, then do
If those don't help then you would be well advised to read through some
or all of the Java Tutorial, especially the parts about I/O:
> BTW, is it that getOutputStream and getInputStream always have to
> appear in a pair? Because I think that getInputStream() in this code
> does not have any functioning, so I removed it, but things went wrong
Again, it depends. In general, however, it would be atypical for there
to be a requirement for the two to occur together. As far as I know
there is no such dependency inherent in any of the platform API classes,
but whether it would be required by the resource providing the streams
(e.g. a web server) is another question entirely.
> HttpURLConnection con = (HttpURLConnection)url.openConnection();
> OutputStreamWriter outStream = new OutputStreamWriter(new
You cannot use a variable (outStream in this case) before it is
declared, so the above code is already painfully mangled. When
outStream _is_ declared, it is initialized with an OutputStreamWriter
wrapped around a BufferedOutputStream wrapped around the OutputStream
associated with the HttpURLConnection referenced by con. You could use
outStream to send Strings or or other character data through the connection.
> BufferedReader in = new BufferedReader(new
Similarly, this declares a reference variable "in" of type
BufferedReader, and initializes it with a BufferedReader wrapped around
an InputStreamReader wrapped around the InputStream associated with con.
Using this reference you could read character data sent to you from
the other side of the connection. The "con.getInputStream()" is
critical there, as it specifies the source of the data that will be read
via variable "in".
You do have a dangerous situation here in that you are using the
client's default character encoding for converting byte streams to
character streams and vise versa; this is prone to breakage. You also
have a poor choice of name in "outStream", which suggests to me that it
contains a reference to an OutputStream. "outWriter" or even plain
"out" would be better.