Re: Another topic on how to read a binary file.
Knitter wrote:
Hi,
I know this has been asked a few zillion times but I couldn't find a
good answer for my problem.
I have a binary file, the Ant Movie Catalog database if anyone knows
the software. It is a file where information about movies is stores,
the software was created in Delphi so the binary files contains Pascal
strings and integers.
I know the file format, for example, I know that the strings are store
using a 4 bytes integer representing the string length, followed by
the actually string. What I'm falling to understand is how to read the
file.
I've been using BufferedInputStream created with a FileInputStream.
If I use the read(byte[]) method, that fills the passed array with the
array.lenght how can I transform that array of bytes into the integer
that I need?
I'm creating a simple test applications to learn how to read the
binary file. I'm starting with the header that is represented as:
strFileHeader35 = ' AMC_3.5 Ant Movie Catalog 3.5.x www.buypin.com
www.antp.be ';
OwnerName: string;
OwnerSite: string;
OwnerMail: string;
OwnerDescription: string;
So I thought of reading the 4 byte that tells me how long each string
is, convert the array with the 4 bytes into the needed integer and
then reading the string into another array with the size of the
integer I have found.
I'm stuck with how to correctly read the file, how to convert the
bytes into integers.
I'm I going the wrong way?
Thanks.
Use a ByteBuffer. After you have read a buffer of data into your app. you wrap a
ByteBuffer around it:
ByteBuffer bb = ByteBuffer.wrap(buffer);
then you can read from the ByteBuffer using its methods, .getShort(), getInt(),
getLong(), getFloat() etc.
If the data is little-endian rather than big endian then, prior to reading data
from the ByteBuffer, set the order using bb.order(ByteOrder.LITTLE_ENDIAN).
So, to read a string you could do something like (I prefer to use
DataInputStream as it has the readFully() method, removing the necessity to
loop over a read() method) :
in = new FileInputStream( file );
dataIn = new DataInputStream( in );
// read the string length
byte[] lengthBytes = new byte[4];
dataIn.readFully( lengthBytes );
// wrap the byte array in a ByteBuffer
ByteBuffer bb = ByteBuffer.wrap( lengthBytes );
// if reading little endian data
bb.order( ByteOrder.LITTLE_ENDIAN );
int stringLength = bb.getInt();
byte[] stringBytes = new byte[stringLength];
dataIn.readFully( stringBytes );
You now have the string as a byte array. You now need to convert that to a Java
String, how you do that depends on the string encoding.
--
Nigel Wade, System Administrator, Space Plasma Physics Group,
University of Leicester, Leicester, LE1 7RH, UK
E-mail : nmw@ion.le.ac.uk
Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555