TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
代码如下:
- [img]http://img.javaxxz.com/2014/10/11/070948281.gif[/img]
- import java.io.*;
- import javax.microedition.io.*;
- import javax.microedition.lcdui.*;
- import javax.microedition.midlet.*;
复制代码
- public class HttpTXT extends MIDlet implements CommandListener {
- private Command exitCommand, loadCommand;
- private Form mainForm;
- private TextField tfItem;
- private TextField tf;
- public HttpTXT() {
- mainForm = new Form("下载并显示文本文件");
- tf = new TextField("文本地址", "http://127.0.0.1/test/test.txt", 120,
- TextField.URL);
- //设置控件的布局
- tf.setLayout(Item.LAYOUT_NEWLINE_AFTER);
- tfItem = new TextField("文本内容", "", 500, TextField.ANY);
- tfItem.setPreferredSize(mainForm.getWidth(), 200);
- tfItem.setLayout(Item.LAYOUT_VEXPAND | Item.LAYOUT_2);
- mainForm.append(tf);
- minForm.append(tfItem);
- exitCommand = new Command("退出", Command.EXIT, 1);
- loadCommand = new Command("下载", Command.SCREEN, 1);
- mainForm.addCommand(exitCommand);
- mainForm.addCommand(loadCommand);
- mainForm.setCommandListener(this);
- }
- protected void startApp() throws MIDletStateChangeException {
- Display.getDisplay(this).setCurrent(mainForm);
- }
- protected void pauseApp() {
- }
- protected void destroyApp(boolean p1) {
- }
- public void commandAction(Command c, Displayable d) {
- if (c == exitCommand) {
- destroyApp(false);
- notifyDestroyed();
- } else if (c == loadCommand) {
- //开启一个新的网络连接后台线程
- new DownLoadTXT(mainForm, tfItem, tf.getString());
- }
- }
- private class DownLoadTXT extends Thread {
- private String txtURL;
- private Form form;
- private TextField tfItem;
- public DownLoadTXT(Form f, TextField i, String url) {
- form = f;
- tfItem = i;
- txtURL = url;
- this.start();
- }
- public void run() {
- String str = null;
- try {
- str = getText(txtURL);
- } catch (Exception e) {
- System.out.println("错误 " + e.getMessage());
- }
- form.setTicker(null);
- if (tfItem != null)
- tfItem.setString(str);
- }
- public String getText(String url) throws IOException, Exception {
- HttpConnection c = null;
- InputStream is = null;
- String str =null;
- try {
- c = (HttpConnection) Connector.open(url);
- //判断是否连接成功
- int rc = c.getResponseCode();
- if (rc != HttpConnection.HTTP_OK) {
- throw new Exception(c.getResponseMessage());
- }
- //获得文本的二进制数据
- is = c.openInputStream();
-
- int length = (int) c.getLength();
-
- if (length > 0) {
- byte servletData[] = new byte[length];
- is.read(servletData);
- str = new String(servletData);
- }
-
-
- } catch (IOException e) {
- System.out.println("错误:" + e.getMessage());
- } finally {
- if (is != null)
- is.close();
- if (c != null)
- c.close();
- }
- return str;
- }
- }
- }
-
复制代码
源码下载:http://203.93.208.26/kj/cwb/dir7/HttpTXT.zip |
|