Writing Binary Data


DataOutputStream out =    new DataOutputStream(socket.getOutputStream()); out.write(byteArray, 0, 10);



In a previous phrase in this chapter, "Writing Text," we showed how to write text data across a network. In this phrase, we show how to write binary data across a network. This phrase assumes that we've previously created a socket to the server from which we want to write text. See the phrase "Contacting a Server" in this chapter for more details on creating the socket instance.

In this phrase, we call the getOutputStream() method of the socket instance to obtain a reference to the socket's output stream. We then instantiate a DataOutputStream, which we can use to write binary data across the network. We use the write() method to write an array of bytes across the network. The write() method takes three parameters. The first parameter is a byte[] to get the bytes to write from. The second parameter is an offset into the byte array to begin writing from. The third parameter is the number of bytes that you want to write. So, in this phrase, we write bytes from the byteArray array, beginning at offset 0, and we write a total of 10 bytes.

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

DataOutputStream out = new DataOutputStream(    new BufferedOutputStream(       socket.getOutputStream()));


Here, instead of directly passing the socket's output stream to the DataOutputStream constructor, we first create a BufferedOutputStream instance and pass that to the DataOutputStream constructor.

In this phrase, we used the write() method, but the DataOutputStream has many other methods available to write data from any primitive Java data type. The available methods for writing binary data include: write(), writeBoolean(), writeByte(), writeBytes(), writeChar(), writeChars(), writeDouble(), writeFloat(), writeInt(), writeLong(), and writeShort(). See the JavaDoc for details on using these methods and other methods of the DataOutputStream class: http://java.sun.com/j2se/1.5.0/docs/api/java/io/DataOutputStream.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