0

I have an inputstream that gets a byte array every few seconds. I know the byte array contains always one long, one double and one integer in this order. Is it possible to read this values with an inputstream (e.g. DataInputStream) or what can you suggest me?

2
  • You can use a DataInputStream, just like you said. Do you have any reason not to? Commented Jul 7, 2013 at 19:09
  • No, I don't really know, how to combine the bytearrayinputstream with the normal inputstream Commented Jul 7, 2013 at 19:13

2 Answers 2

2

You should look into wrapping a ByteBuffer using:

ByteBuffer buf=ByteBuffer.wrap(bytes)
long myLong=buf.readLong();
double myDbl=buf.readDouble();
int myInt=buf.readInt();

The DataInputStream will do fine, though with worse performance:

DataInputStream dis=new DataInputStream(new ByteArrayInputStream(bytes));
long myLong=dis.readLong();
double myDbl=dis.readDouble();
int myInt=dis.readInt();

To get strings from either of these, you can use getChar() repeatedly.

Assuming buf is your ByteBuffer or DataInputStream, do the following:

StringBuilder sb=new StringBuilder();
for(int i=0; i<numChars; i++){ //set numChars as needed
    sb.append(buf.readChar());
}
String myString=sb.toString();

If you want to read until the end of the buffer, change the loop to:

readLoop:while(true){
    try{
        sb.append(buf.readChar());
    catch(BufferUnderflowException e){
        break readLoop;
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you. When the byte array contains a string. Is it also possible to read this with the datainputstream?
@Maxii Yes, by way of repeated readChar()s and StringBuilder. If you'd like I can add it to the answer.
@Maxii On this post and other questions of yours, please mark the answer that helped you the most as accepted using the checkmark below the voting buttons.
Is that right, that your solution with the stringbuilder only works, when i know the length of the string? Or how can I get the numChars value?
@Maxii If the string is at the end of the buffer you can turn it into a while loop as I'll edit into my post.
|
2

You can look into java.nio.ByteBuffer which provides the methods getLong(), getDouble() and getInt().

Assuming you got an arbitrary InputStream with always 20 bytes (8 byte Long, 8 byte Double, 4 byte Int):

int BUFSIZE = 20;
byte[] tmp = new byte[BUFSIZE];

while (true) {
    int r = in.read(tmp);
    if (r == -1) break;
}

ByteBuffer buffer = ByteBuffer.wrap(tmp);
long l = buffer.getLong();
double d = buffer.getDouble();
int i = buffer.getInt();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.