Tuesday 19 October 2010

Random reading for Java Mobile

The lack of the RandomAccessFile class in J2ME's File API is quite a trouble when implementing something more advanced. It's especially true, if one needs to read some binary file in a non-linear fashion. To remedy this I wrote the AlbiteRandomReadingFile API that implements some similar functionality.

The important part is its ability to seek and obtain the pointer, i.e. the current position in the currently open file.
The RandomAccessFile class extends InputStream and implements DataInput and Connection interfaces.
It's based on FileConnection from the File API. Unfortunately, there is no way to have effective seeking using this API, so seeking is actually achieved through opening the InputStream anew and skipping bytes (which itself isn't optimally implemented either, but that is not my fault). However, there is at least the fact, that some skipping can be avoided, if the seeking position is at or after the current position of the file pointer. In such cases the stream doesn't have to be reopened, and there is less bytes to skip. This simple optimization is integrated in the API.
Note that it's made for CLDC 1.1 and in order to make it work in CLDC 1.0, one has to remove the readDouble() and readFloat() methods.
The code is open source and is available at GitHub.

No comments:

Post a Comment