取决于你从哪里得到这 4 个字节:
http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#readInt()
http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#getInt(int)
您当然仍然可以手动执行,但在大多数情况下使用其中之一(如果您必须转换具有大量字节的字节数组,您可能希望在 ByteArrayInputStream 周围使用 DataInputStream ) 更容易。
编辑:如果需要更改字节序,则必须使用 ByteBuffer,或者自己反转字节,或者自己进行转换,因为 DataInput 不支持更改字节序。
Edit2:当您从套接字输入流中获取它们时,我会将其包装到DataInputStream 中,并使用它来读取各种数据。特别是因为 InputStream.read(byte[]) 不能保证填充整个字节数组...... DataInputStream.readFully 会。
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);
Edit3:从流中多次读取时,它们将继续从您停止的位置读取,即。 e. aByte 将是字节 0,anInt 将是字节 1 到 4,anInt 将是字节 5 到 8,等等。 readFully 将在所有这些之后继续读取并阻塞,直到它读取 lotOfbytes。
当流停止(连接断开)时,您将获得 EOFException 而不是 -1,因此如果您获得 -1,则 int 确实是 -1。
如果您根本不想解析任何字节,您可以跳过()它们。使用 DataInputStream 无法以 2 种不同的方式解析一个字节(即首先从字节 0 到 3 读取一个 int,然后从字节 2 到 5 读取一个),但通常也不需要。
例子:
// 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.
希望这能回答您的其他问题。