This page was last modified 23:05, 14 March 2008.
How to write data to a file in Java ME
From Forum Nokia Wiki
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.
The full source code for a test MIDlet:
WriteMIDlet.java
import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.file.*; import javax.microedition.io.*; import java.io.*; public class WriteMIDlet extends MIDlet implements CommandListener { private TextBox textbox; private String photos = "fileconn.dir.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); textbox.addCommand(saveCommand); textbox.addCommand(exitCommand); textbox.setCommandListener(this); Display.getDisplay(this).setCurrent(textbox); 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(); FileConnection fconn = (FileConnection)Connector.open(url, Connector.READ_WRITE); if (!fconn.exists()) { fconn.create(); } OutputStream ops = fconn.openOutputStream(); ops.write(data); ops.close(); fconn.close(); } 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(); } }
| Related Discussions | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Writing TUint on to socket? | sumitv | General Symbian C++ | 8 | 2007-04-12 06:36 |
| Cannot Write To File | mubx2000 | General Symbian C++ | 13 | 2006-10-24 14:48 |
| (Bluetooth)RunL is not called after Write | liuvictor2005 | Symbian Networking & Messaging | 4 | 2008-03-07 03:19 |
| HTTP file post problem | Dattanand | Symbian Networking & Messaging | 10 | 2008-03-17 05:54 |
| accessing rms.db in j2me | niraj_gandhi | Mobile Java General | 16 | 2007-02-10 08:27 |
