Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no readUnsignedInt in RandomAccessFile class?

Tags:

java

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?

like image 801
5YrsLaterDBA Avatar asked May 20 '11 20:05

5YrsLaterDBA


People also ask

What is the difference between the file and RandomAccessFile classes?

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.

Which method in the RandomAccessFile class provides for random access?

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.

What is the use of RandomAccessFile?

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.

Which method is used in RandomAccessFile class to get the current location of the file pointer?

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.


2 Answers

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.

like image 73
musiKk Avatar answered Nov 15 '22 20:11

musiKk


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)?

like image 37
Chris Morgan Avatar answered Nov 15 '22 20:11

Chris Morgan