Search code examples
java-merandom-access

File random access in J2ME


does J2ME have something similar to RandomAccessFile class, or is there any way to emulate this particular (random access) functionality?

The problem is this: I have a rather large binary data file (~600 KB) and would like to create a mobile application for using that data. Format of that data is home-made and contains many index blocks and data blocks. Reading the data on other platforms (like PHP or C) usually goes like this:

  1. Read 2 bytes for index key (K), another 2 for index value (V) for the data type needed
  2. Skip V bytes from the start of the file to seek to a file position there the data for index key K starts
  3. Read the data
  4. Profit :)

This happens many times during the program flow.

Um, and I'm investigating possibility of doing the very same on J2ME, and while I admit I'm quite new to the whole Java thing, I can't seem to be able to find anything beyond InputStream (DataInputStream) classes which don't have the basic seeking/skipping to byte/returning position functions I need.

So, what are my chances?


Solution

  • You should have something like this

    try {
        DataInputStream di = new DataInputStream(is);
        di.marke(9999);
        short key = di.readShort();
        short val = di.readShort();
        di.reset();
        di.skip(val);
        byte[] b= new byte[255];
        di.read(b);
    }catch(Exception ex ) {
        ex.printStackTrace();
    }
    

    I prefer not to use the marke/reset methods, I think it is better to save the offset from the val location not from the start of the file so you can skip these methods. I think they have som issues on some devices.

    One more note, I don't recommend to open a 600 KB file, it will crash the application on many low end devices, you should split this file to multiple files.