Here's just this example:
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
Why it feels s开发者_如何学JAVAo strange?
You are actually looking at two different kinds of stream.
The Writer
/ Reader
classes and subclasses are for reading / writing character-based data. It takes care of conversion between Java's internal UTF-16 representation of text and the character encoding used outside. The BufferedReader
class adds a readLine()
method that understands end-of-line makers.
The InputStream
/ OutputStream
classes and subclasses are for reading and writing byte-based data without any assumptions about character encodings, or that the data is text. Since it eschews these assumptions, "line" has no clear meaning, and hence the BufferedInputStream
class does not have a readLine()
method.
(Incidentally, DataInputStream
does have a readLine()
method, but it is deprecated because it is broken. It makes assumptions about encodings, etc that are invalid on some platforms!)
In your particular example, the code is asymmetric because the HTTP service it designed to talk to is asymmetric. The service expects a request with binary content (encoded using the DataOutputStream
wrapper), and delivers a response with text content. This is not particularly unusual ... or wrong.
The strangeness of writing the "input" to a server to an "output" is merely a matter of perspective. In simple terms, an OutputStream / Writer is something you "write to" (i.e. a data sink) and an InputStream or Reader is something you "read from" (i.e. a data source). That's just the way it is, and it is not strange at all once you get used to it.
Actually, we don't. There is no method readLine defined in InputStream. It also operates on bytes only, just like OutputStream.
In the code you referenced, readLine is called on a BufferedReader.
Reader and Writer are for text data and operate on characters (and Strings), InputStream and OutputStream work with binary data (raw bytes). To convert between the two (i.e. wrap an InputStream into a Reader or an OutputStream into a Writer), you need to choose a character set.
I'm feeling strange why not read out from OutputStream but from InputStream
That's just a matter of perspective.
An OutputStream or a Writer is where you write your output to.
An InputStream or a Reader is where you read your input from.
Of course, somewhere, on the other end of the stream, someone might treat your OutputStream as their InputStream ...
readLine
does exactly what the name implies -- it reads a line of text until the end-of-line marker.
When you write to a stream, you already know where your line ends.
If you are looking for a way to write to streams in a more intuitive way, try PrintWriter
.
精彩评论