J2ME: Read an Image from the Device Filesystem

Posted by & filed under , .

As you’ve seen with previous posts, I’m trying to make sure that all the stuff that used to be on my old website and people are still looking for is being brought back to light; and one of the search terms that I see redirecting people to my website is “j2me read file” — for which there used to be this article on my old website, so here it is again:

Quite often in your mobile application you might need to allow the user to specify an image that s/he has already stored in the device filesystem (e.g. mobile memory, memory stick etc). This piece of code shows you how to read the image from the filesystem assuming you already have the file name.

Note that this can only apply to devices that support the FileConnection API (JSR 75). For details on this JSR, please visit the Java Community Process on www.jcp.org.

Simply add the following function to your class and invoke it with the filename:

protected Image createImage( String name ) throws IOException {
   InputStream is = Connector.openInputStream( "file:///" + name );
   int read;
   byte readData[] = null;
   while( (read = is.read(buffer)) != -1 ) {
      if( readData == null ) {
         readData = new byte[read];
         System.arraycopy( buffer, 0, readData, 0, read );
      } else {
         byte tmp[] = new byte[readData.length + read];
         System.arraycopy( readData, 0, tmp, 0, readData.length );
         System.arraycopy( buffer, 0, tmp, readData.length, read );
         readData = null; // suggest to the gc that we don't need it!
         readData = tmp;
         tmp = null; // suggest to the gc that we don't need it!
      }
   }
   is.close();
   Image img = Image.createImage( readData, 0, readData.length );
   return img;
}

NOTE: As stated above, this is an old article — as such, the JSR’s and API’s involved might have changed/improved so this is not necessarily up-to-date (or correct!). I haven’t reviewed this article and not planning to do so in the near future — it might be the case that the code is still correct, but if it isn’t, please be aware I won’t be able to address this in the near future. However, should you have comments/suggestions about the above code, I would be more than glad to hear them and even post an updated code if this is no longer the best way of doing this.

2 Responses to “J2ME: Read an Image from the Device Filesystem”

  1. Vijay

    Dear Mr. Liviu Tudor ,
    This code will throw NullPointer exception while creating image from readData byte array variable because you make it to be null on every iteration.

  2. Liv

    Vijay, please look at the code again and notice that it’s only set to null prior to being assigned the value of tmp — as such it’s not really null. Run it and see for yourself.
    Thank you for the heads-up though!

Leave a Reply

Your email address will not be published.