This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I would never have guessed that working at the byte level in Java would be so tough. I'm having to work with a structured blob that is retrieved from a database. The structured blob is a series of tokenized data in the following form: 2-byte (int) Token ID 2-byte (int) Date Type 2-byte (int) Data Length n-byte (?) Data value If I load this structured blob into a byte array, how do I extract these binary and other values from the array and put them into particular variables?
I'd say the easiest way to do this in Java is something like
Note that when using DataInputStream, detecting the end of file can be a bit messy. Using available() works here because the underlying ByteArrayInputStream is guaranteed to have the entire array available - you won't see available() return 0 unless there really are no more bytes to read. However this is not the case for other types of streams - if you were reading from a socket for example, you'd have to allow that when available() == 0 it might just mean that the remaining bytes haven't been sent yet, for example. So be careful about using available() in other circumstances.
"I'm not back." - Bill Harding, Twister
Joined: Sep 13, 2002
Thanks Jim for the suggestion. I'll play with this to see how it plays out. Gary
Joined: Jan 30, 2000
Oops, just noticed. If those integer values are stored using only two bytes, you can't use readInt() - you probably need readShort() or readUnsignedShort(). You can read the API for DataInputStream to see exactly what each one does. If it's not what you need exactly, don't overlook other methods - DataInputStream has a lot of different things it can do.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com