java如何解析字节数组
时间: 2023-08-18 07:08:34 浏览: 46
Java中可以使用ByteArrayInputStream和DataInputStream类来解析字节数组。
ByteArrayInputStream类将字节数组封装成一个输入流,可以使用read()方法从中读取数据。而DataInputStream类可以从输入流中读取Java基本数据类型的值。
以下是一个示例代码:
```java
byte[] byteArray = {0x01, 0x02, 0x03, 0x04, 0x05};
ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
DataInputStream dis = new DataInputStream(bais);
try {
int intValue = dis.readInt();
short shortValue = dis.readShort();
byte byteValue = dis.readByte();
System.out.println(intValue + ", " + shortValue + ", " + byteValue);
} catch (IOException e) {
e.printStackTrace();
}
```
在上面的代码中,我们首先定义了一个字节数组byteArray,然后使用ByteArrayInputStream类将其封装成了一个输入流bais。接着,我们使用DataInputStream类从输入流中读取int、short和byte类型的值,并输出到控制台中。
需要注意的是,使用DataInputStream类时,读取的数据类型必须与字节数组中存储的数据类型一致,否则会抛出EOFException异常。