I just found there is no readUnsignedInt
() method in the RandomAccessFile
class. Why? Is there any workaround to read an unsigned int out from the file?
Edit:
I want to read an unsigned int from file and put it into a long space.
Edit2:
Cannot use readLong(). it will read 8 bytes not 4 bytes. the data in the file have unsigned ints in 4 bytes range.
Edit3:
Found answer here: http://www.petefreitag.com/item/183.cfm
Edit4:
how about if the data file is little-endian? we need to bits swap first?
File is an abstract representation of a file/directory which may or may not even exist. It doesn't consume any resources, so you can store them as much as you want. RandomAccessFile is for actual file access (reading, seeking, writing), so you don't need it here.
RandomAccessFile Class provides a way to random access files using reading and writing operations. It works like an array of byte storted in the File. Syntax : public int read() Parameters : -------- Return : reads byte of data from file, -1 if end of file is reached.
Java RandomAccessFile provides the facility to read and write data to a file. RandomAccessFile works with file as large array of bytes stored in the file system and a cursor using which we can move the file pointer position.
For a RandomAccessFile raf, the raf. seek(position) method moves the file pointer to a specified location. raf. seek(0) moves the file pointer to the beginning of the file, and raf.
I'd do it like this:
long l = file.readInt() & 0xFFFFFFFFL;
The bit operation is necessary because the upcast will extend a negative sign.
Concerning the endianness. To the best of my knowledge all I/O in Java is done in big endian fashion. Of course, often it doesn't matter (byte arrays, UTF-8 encoding, etc. are not affected by endianness) but many methods of DataInput
are. If your number is stored in little endian, you have to convert it yourself. The only facility in standard Java I know of that allows configuration of endianness is ByteBuffer
via the order()
method but then you open the gate to NIO and I don't have a lot of experience with that.
Edited to remove readLong()
:
You could use readFully(byte[] b, int off, int len)
and then convert to Long
with the methods here: How to convert a byte array to its numeric value (Java)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With