Java Tutorial/J2ME/OutputConnection — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:00, 1 июня 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);
      }
    }
  }
}