Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Revision as of 01:29, 26 July 2013 by hamishwillee (Talk | contribs)

How to write data to a file in Java ME

From Wiki
Jump to: navigation, search

This article shows, how to write data to a file by using FileConnection API (JSR-75). This example MIDlet has a TextBox, where text can be entered. Then the text can be saved to readme.txt file, which is in this case created under Gallery's Images folder. {{ArticleMetaData |sourcecode= [[ |installfile= [[ |devices= Nokia Asha 501, Nokia C3-01, Nokia Asha 306, Nokia E7-00 |sdk= Nokia Asha SDK 1.0 (beta), Nokia SDK 1.1 for Java, Nokia SDK 2.0 for Java (beta), Nokia Symbian SDKs |dependencies= |signing= |capabilities= |language= |translated-by= |translated-from-title= |translated-from-id= |review-by= skalogir |review-timestamp= 20130509 |update-by= |update-timestamp= |creationdate= 20090128 |author= jarmlaht |platform= Nokia Asha Platform 1.0 and later, Series 40 DP 1.0 and later, Nokia Belle }}

Source code:

The full source code for a test MIDlet:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class WriteMIDlet extends MIDlet implements CommandListener {
private TextBox textbox;
private String photos = "";
private Command saveCommand;
private Command exitCommand;
private String path;
public void startApp() {
textbox = new TextBox("WriteMIDlet", "", 1000, TextField.ANY);
saveCommand = new Command("Save", Command.SCREEN, 1);
exitCommand = new Command("Exit", Command.EXIT, 1);
path = System.getProperty(photos);
public void pauseApp() {
public void destroyApp(boolean unconditional) {
private void saveFile(String path, String name) {
try {
String url = path + name;
String string = textbox.getString();
byte data[] = string.getBytes("UTF-8");
FileConnection fconn = (FileConnection), Connector.READ_WRITE);
if (!fconn.exists()) {
OutputStream ops = fconn.openOutputStream();
catch (IOException ioe) {
System.out.println("IOException: "+ioe.getMessage());
catch (SecurityException se) {
System.out.println("Security exception:" + se.getMessage());
public void commandAction(Command c, Displayable d) {
if (c == saveCommand) saveFile(path, "readme.txt");
if (c == exitCommand) this.notifyDestroyed();

See also

247 page views in the last 30 days.