记一次二进制文件的读取解析
背景
现有需求入下:
c的同事将流量数据以二进制形式追加写入文件中,需要java端读取并解析,发送至kafka。
c的数据类型
Specifier | Common Equivalent | Signing | Bits | Bytes | Minimum Value | Maximum Value |
---|---|---|---|---|---|---|
int8_t | signed char | Signed | 8 | 1 | -128 | 127 |
uint8_t | unsigned char | Unsigned | 8 | 1 | 0 | 255 |
int16_t | short | Signed | 16 | 2 | -32,768 | 32,767 |
uint16_t | unsigned short | Unsigned | 16 | 2 | 0 | 65,535 |
int32_t | int | Signed | 32 | 4 | -2,147,483,648 | 2,147,483,647 |
uint32_t | unsigned int | Unsigned | 32 | 4 | 0 | 4,294,967,295 |
int64_t | long long | Signed | 64 | 8 | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
uint64_t | unsigned long | long | Unsigned | 64 | 8 | 0 |
Java中的数据类型
java是没有无符号的概念的,有时候需要特殊处理
JAVA API的支持
可以看一下DataInputStream类的实现
// DataInputStream
class DataInputStream extends FilterInputStream implements DataInput {
/**
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end
* of the stream has been reached.
* @exception IOException if the first byte cannot be read for any reason
* other than end of file, the stream has been closed and the underlying
* input stream does not support reading after close, or another I/O
* error occurs.
* @see java.io.FilterInputStream#in
* @see java.io.InputStream#read(byte[], int, int)
*/
public final int read(byte b[]) throws IOException {
return in.read(b, 0, b.length);
}
/**