Best way to read structured binary files with Java

前端 未结 12 911
我寻月下人不归
我寻月下人不归 2020-12-04 13:23

I have to read a binary file in a legacy format with Java.

In a nutshell the file has a header consisting of several integers, bytes and fixed-length char arrays, f

12条回答
  •  -上瘾入骨i
    2020-12-04 13:51

    I would create an object that wraps around a ByteBuffer representation of the data and provide getters to read directly from the buffer. In this way, you avoid copying data from the buffer to primitive types. Furthermore, you could use a MappedByteBuffer to get the byte buffer. If your binary data is complex, you can model it using classes and give each class a sliced version of your buffer.

    class SomeHeader {
        private final ByteBuffer buf;
        SomeHeader( ByteBuffer fileBuffer){
           // you may need to set limits accordingly before
           // fileBuffer.limit(...)
           this.buf = fileBuffer.slice();
           // you may need to skip the sliced region
           // fileBuffer.position(endPos)
        }
        public short getVersion(){
            return buf.getShort(POSITION_OF_VERSION_IN_BUFFER);
        }
    }
    

    Also useful are the methods for reading unsigned values from byte buffers.

    HTH

提交回复
热议问题