Read a File In J2ME

by Manoj Alwis

Hi friends, this month j2me lesson I will describe how we can read a specified file in J2ME. Actually in here you can read lot of file formats and can get file data as an input to the J2ME program. In this application I will creating a “help.txt” file and read data of this file by the help of J2ME Midlet.
First of all, you have to open j2me project on Netbeans IDE, then create package like src. After that right click on the src package and select MIDlet and name it as ReadDisplayFile.Then you have to create text file “help.txt” on src package, it contains “!!!!!!!!!Welcome To diGIT IT Magzine!!!!!!!!!!!”.

1.When you run the Application you can see following application

2.After clicking Launch button then click Help button then you can see “help.txt” file data

3.Source code

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
* @author Manoj Alwis
public class ReadDisplayFile extends MIDlet implements CommandListener
private Display display; // Reference to Display object
private Form fmMain; // Main form
private Command cmHelp; / / Command to show a help file
private Command cmExit; // Command to exit the MIDlet
private Alert alHelp; // Alert to display help file text
public ReadDisplayFile()
display = Display.getDisplay(this);
cmHelp = new Command("Help", Command.SCREEN, 1);
cmExit = new Command("Exit", Command.EXIT, 1);
fmMain = new Form("Read File");
public void startApp()

public void pauseApp()
{ }

public void destroyApp(boolean unconditional)
{ }

public void commandAction(Command c, Displayable s)
if (c == cmHelp)
String str;

if ((str = readHelpText()) != null) // Access the resource and read its contents

// Create an Alert to display the help text
alHelp = new Alert("Help", str, null, null);
display.setCurrent(alHelp, fmMain);
else if (c == cmExit)

private String readHelpText()
InputStream is = getClass().getResourceAsStream("help");
StringBuffer sb = new StringBuffer();
int chr, i = 0;

// Read until the end of the stream

while ((chr = != -1)
sb.append((char) chr);

return sb.toString();
catch (Exception e)
System.out.println("Unable to create stream");
return null;


Previous Article

Your rating: None Average: 1 (1 vote)