Byte Array Streams
It’s sometimes convenient to use stream methods to manipulate
data in byte arrays. For example, you might receive an array of raw
bytes that you want to interpret as double-precision, floating-point
numbers. (This is common when using UDP to transfer data across the
Internet, for one example.) The quickest way to do this is to use a
DataInputStream
. However, before you can create a
data input stream, you first need to create a raw, byte-oriented
stream. This is what the
java.io.ByteArrayInputStream
class gives you. Similarly, you might want to send a group of
double-precision, floating-point numbers across the network with UDP.
Before you can do this, you have to convert the numbers into bytes.
The simplest solution is to use a data output stream chained to a
java.io.ByteArrayOutputStream
. By chaining the
data output stream to a byte array output stream, you can write the
binary form of the floating-point numbers into a byte array, then
send the entire array in a single packet.
Get Java I/O now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.