I tried this code:
Code:
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class MIDletfinal extends MIDlet implements CommandListener {
Command save, exit;
TextBox text;
Display display;
public MIDletfinal() {
text = new TextBox("", "", 400, TextField.ANY);
save = new Command("Save", Command.SCREEN, 1);
exit = new Command("Exit", Command.EXIT, 1);
text.addCommand(save);
text.addCommand(exit);
text.setCommandListener(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
display.setCurrent(text);
}
public void commandAction(Command arg0, Displayable arg1) {
if (arg0 == save) {
saveFile();
// Alert used for notify the user that the file had already been
// saved
Alert alert = new Alert("File saved.");
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, this.text);
}
if (arg0 == exit)
;
{
try {
destroyApp(true);
this.notifyDestroyed();
} catch (MIDletStateChangeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void saveFile() {
try {
// Creating a connection.
FileConnection c = (FileConnection) Connector.open(System
.getProperty("fileconn.dir.photos")
+ "bruno/", Connector.READ_WRITE);
// Checking if the directoy exists or not. If it doesn't exist we
// create it.
if (c.exists()) {
System.out.println("existe");
} else {
System.out.println("nao existe");
c.mkdir();
c = (FileConnection) Connector.open(System
.getProperty("fileconn.dir.photos")
+ "bruno/thiago.txt", Connector.READ_WRITE);
// create the file
c.create();
// create an OutputStream
OutputStream out = c.openOutputStream();
// Get the user text
String userText = text.getString();
// write out the user's text into the file
out.write(userText.getBytes());
out.flush();
out.close();
// Never forget to close a connection or you can face problems.
// Pay attention here! If you close the connection before and
// later try to
// write something it will throw an exception.
c.close();
// Openning the file again and
// show what was saved in console.
c = (FileConnection) Connector.open(System
.getProperty("fileconn.dir.photos")
+ "bruno/thiago.txt", Connector.READ_WRITE);
//
InputStream in = c.openInputStream();
byte[] b = new byte[50];
in.read(b);
System.out.println(new String(b, 0, b.length));
}
} catch (Exception e) {
}
}
}