Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Depending on where you get those 4 bytes from:</p> <p><a href="http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#readInt()" rel="nofollow noreferrer">http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#readInt()</a></p> <p><a href="http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#getInt(int)" rel="nofollow noreferrer">http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#getInt(int)</a></p> <p>You can of course still do it manually, but in most cases using one of those (if you have to convert a byte array with lots of bytes, you might want to use a <code>DataInputStream</code> around a <code>ByteArrayInputStream</code> for example) is easier.</p> <p><strong>Edit</strong>: If you need to change the endianness, you will have to use a ByteBuffer, or reverse the bytes yourself, or do the conversion yourself, as DataInput does not support changing the endianness.</p> <p><strong>Edit2</strong>: When you get them from the socket input stream, I'd wrap that one into a <code>DataInputStream</code> and use it for reading all kinds of data. Especially since InputStream.read(byte[]) will not guarantee to fill the whole byte array... DataInputStream.readFully does.</p> <pre><code>DataInputStream in = new DataInputStream(socket.getInputStream()); byte aByte = in.readByte(); int anInt = in.readInt(); int anotherInt = in.readInt(); short andAShort = in.readShort(); // 11 bytes read :-) byte[] lotOfBytes = new byte[anInt]; in.readFully(lotOfBytes); </code></pre> <p><strong>Edit3</strong>: When reading multiple times from a stream, they will continue reading where you stopped, i. e. aByte will be byte 0, anInt will be bytes 1 to 4, anotherInt will be bytes 5 to 8, etc. readFully will read on after all that and will block until it has read <code>lotOfbytes</code>.</p> <p>When the stream stops (the connection drops) you will get <code>EOFException</code> instead of -1, so if you get -1, the int really was -1.</p> <p>If you do not want to parse any bytes at all, you can skip() them. Parsing one byte in 2 different ways is not possible with DataInputStream (i. e. read first an int from byte 0 to 3, then one from byte 2 to 5), but usually not needed either.</p> <p>Example:</p> <pre><code>// read messages (length + data) until the stream ends: while (true) { int messageLength; try { messageLength = in.readInt(); // bytes 0 to 3 } catch (EOFException ex) { // connection dropped, so handle it, for example return; } byte[] message = new byte[messageLength]; in.readFully(message); // do something with the message. } // all messages handled. </code></pre> <p>Hope this answers your additional questions.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload