File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes extracting bytes from byte array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "extracting bytes from byte array" Watch "extracting bytes from byte array" New topic
Author

extracting bytes from byte array

Gary Frick
Greenhorn

Joined: Sep 13, 2002
Posts: 28
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?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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
Gary Frick
Greenhorn

Joined: Sep 13, 2002
Posts: 28
Thanks Jim for the suggestion. I'll play with this to see how it plays out. Gary
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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 agree. Here's the link: http://aspose.com/file-tools
 
subject: extracting bytes from byte array