Reading Binary Data


DataInputStream in =    new DataInputStream(socket.getInputStream()); in.readUnsignedByte();



In this phrase, we show how to read binary data across a network. 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.

In this phrase, we call the getInputStream() method of the socket instance to obtain a reference to the socket's input stream. Passing the input stream as a parameter, we instantiate a DataInputStream, which we can use to read binary data across the network. We use the readUnsignedByte() method to read a single unsigned byte across the network.

If the volume of data that you are reading is large, it will be more efficient to wrap the socket's input stream in a BufferedInputStream instance. Here, we show how this is done:

DataInputStream in = new DataInputStream(    new BufferedInputStream(       socket.getInputStream()));


Here, instead of directly passing the socket's input stream to the DataInputStream constructor, we first create a BufferedInputStream instance and pass that to the DataInputStream constructor.

In this phrase, we used the readUnsignedByte() method, but DataInputStream has many other methods available to read data into any primitive Java data type. The available methods for reading binary data include: read(), readBoolean(), readByte(), readChar(), readDouble(), readFloat(), readInt(), readLong(), readShort(), readUnsignedByte(), and readUnsignedShort(). See the JavaDoc for details on using these methods and other methods of the DataInputStream class: http://java.sun.com/j2se/1.5.0/docs/api/java/io/DataInputStream.html




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