Java Tutorial/J2ME/OutputConnection

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Connect to a file

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.OutputConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class J2MEFileConnection extends MIDlet implements CommandListener {
  private Command exit = new Command("Exit", Command.EXIT, 1), 
                start = new Command("Start", Command.EXIT, 1);
  private Display display;
  private Form form = new Form("Write To File");
  public J2MEFileConnection() {
    display = Display.getDisplay(this);
    form.addCommand(exit);
    form.addCommand(start);
    form.setCommandListener(this);
  }
  public void startApp() throws MIDletStateChangeException {
    display.setCurrent(form);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
      destroyApp(false);
      notifyDestroyed();
    } else if (command == start) {
      try {
        OutputConnection connection = (OutputConnection) Connector.open("file://c:/myfile.txt;append=true", Connector.WRITE);
        OutputStream out = connection.openOutputStream();
        PrintStream output = new PrintStream(out);
        output.println("This is a test.");
        out.close();
        connection.close();
        Alert alert = new Alert("Completed", "Data Written", null, null);
        alert.setTimeout(Alert.FOREVER);
        alert.setType(AlertType.ERROR);
        display.setCurrent(alert);
      } catch (Exception error) {
        Alert alert = new Alert("Error", error.toString(), null, null);
        alert.setTimeout(Alert.FOREVER);
        alert.setType(AlertType.ERROR);
        display.setCurrent(alert);
      }
    }
  }
}