Reading Text


BufferedReader in =    new BufferedReader(new InputStreamReader(       socket.getInputStream())); String text = in.readLine();



This phrase assumes that we've previously created a socket to the server from which we want to read text. See the phrase "Contacting a Server" in this chapter for more details on creating the socket instance. Given the socket instance, we call the getInputStream() method to get a reference to the socket's input stream. With that, we create an InputStreamReader and use it to instantiate a BufferedReader for reading in the text across the network. The readLine() method of the BufferedReader.

Using the BufferedReader as we do in this phrase allows for efficient reading of characters, arrays, and lines. If we were interested in reading only a very small amount of data, we could do this directly from the InputStreamReader, without using a BufferedReader. Here, we show how you could read data into a character array using only an InputStreamReader:

InputStreamReader in =    new InputStreamReader(socket.getInputStream())); String text = in.read(charArray, offset, length);


In this example, data would be read from the input stream into the array of characters specified by charArray. The characters would be placed in the array starting at an offset specified by the offset parameter, and the maximum number of characters read is specified by the length parameter.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net