Code sample: Reading sections of a binary file

This code sample demonstrates how to read sections of a binary file by reading header information from a .gif file. The app reads the width and height of the image from the header. To run the code sample, place a .gif file in the root folder of a media card in a BlackBerry smartphone.

import net.rim.device.api.ui.*;
import net.rim.device.api.io.*;
import javax.microedition.io.file.*;
import javax.microedition.io.*;
import java.io.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;

public class RandomFileAccess extends UiApplication
{
   public static void main(String[] args)
   {
      RandomFileAccess app = new RandomFileAccess();
      app.enterEventDispatcher();
   }
   public RandomFileAccess()
   {
      pushScreen(new HomeScreen());
   }
}

class HomeScreen extends MainScreen
{

   public HomeScreen()
   {
      setTitle("Random File Access Sample");
      try 
      {
         FileConnection fc = (FileConnection)Connector.open("file:///SDCard/test.gif");
         boolean bFileExists = fc.exists();
         if (!bFileExists)
         {
         Dialog.alert("Cannot find specified GIF file.");
         System.exit(0);
         }
         DataInputStream in = fc.openDataInputStream();
         byte[] widthBytes = new byte[2];
         byte[] heightBytes = new byte[2];
		     
         if ( in instanceof Seekable ) 
         {
            ((Seekable) in).setPosition(6);
            in.read(widthBytes,0,2);
		     
            ((Seekable) in).setPosition(8);
            in.read(heightBytes,0,2);
         } 
		     
         int widthPixels  = widthBytes[0]  + 256 * widthBytes[1];
         int heightPixels = heightBytes[0] + 256 * heightBytes[1];
		     
         add(new LabelField("Width: " + widthPixels + "\nHeight: " + heightPixels));
		     
         in.close();
         fc.close();
      }
      catch (IOException ioe) 
      {
         ioe.printStackTrace();
      } 
	} 
}

Was this information helpful? Send us your comments.