I have a specification which tells that the first four bytes refer to a specific value and the next 8 refers to an int and followed by 32 bits for say a particular data type. What is the best way to read such data in java? Is there any standard way or do i just need to 开发者_运维知识库read it by moving the offset by the respective positions
Your best bet if you really need to do this in Java is to create a simple DTO with a custom serialization. Define it's fields according to your protocol format and have it read itself from your byte stream. Something like:
public class ProtocolDTO implements Serializiable {
private int specificValue;
private long anInt;
private int particularDataType;
// Constructors, Accessors
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
specificValue = in.readInt();
anInt = in.readLong();
particularDataType = in.readInt();
}
}
Be careful of endian-ness when reading directly from protocol streams like this. Also, you may need to declare serializable subtypes, depending on what your 'particularDataType' really is.
To read primitive types from a stream, use a DataInputStream and read the appropriate types in order.
http://download.oracle.com/javase/1.4.2/docs/api/java/io/DataInputStream.html
int i1 = stream.readInt();
long l1 = stream.readLong();
Just take care to verify what conventions are being used in the stream, i.e. are ints signed or unsigned an so on. This can be done in a deserialization method as suggested in another answer.
Bit Masking would do
精彩评论