当前位置: 代码迷 >> J2ME >> J2ME上载并读取服务器txt文件
  详细解决方案

J2ME上载并读取服务器txt文件

热度:7575   发布时间:2013-02-25 21:33:05.0
J2ME下载并读取服务器txt文件
J2ME下载并读取服务器txt文件,我用的公司的服务器,大家如果测试代码需要修改为自己的url,本实例是将服务器的txt文件内容添加到TextField显示,当然也可以保存到RMS中,代码如下:





package com.mopietek;import java.io.DataInputStream;import java.io.IOException;import javax.microedition.io.Connector;import javax.microedition.io.HttpConnection;import javax.microedition.lcdui.Command;import javax.microedition.lcdui.CommandListener;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Displayable;import javax.microedition.lcdui.Form;import javax.microedition.lcdui.TextField;import javax.microedition.midlet.MIDlet;import javax.microedition.midlet.MIDletStateChangeException;public class LoadTextMidlet extends MIDlet implements Runnable,CommandListener{		private Display display;	private Thread textThread;		private Form mainForm,textForm;		private TextField textField;		public final static Command exitCommand = new Command("退出",Command.EXIT,1);		public LoadTextMidlet() {			}	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {	}	protected void pauseApp() {	}	protected void startApp() throws MIDletStateChangeException {		display = Display.getDisplay(this);		mainForm = new Form("主窗口");		textForm = new Form("文本窗口");		textField = new TextField("call me 邪道少年","hello",1024,TextField.ANY);		textForm.addCommand(exitCommand);		textForm.setCommandListener(this);		display.setCurrent(mainForm);			    textThread = new Thread(this);	    textThread.start();			}	public void run(){				String URL = "http://dev.mopietek.net:8080/waptest03/down/wap.txt";		String text = loadText(URL); //获取服务器文本		textField.setString(text);		textForm.append(textField);		display.setCurrent(textForm);			}		public String loadText(String url){				HttpConnection hpc = null;		DataInputStream dis = null;				try{			hpc = (HttpConnection) Connector.open(url);			int length = (int) hpc.getLength();			byte[]data = new byte[length];						dis = new DataInputStream(hpc.openInputStream());						dis.readFully(data);						return new String(data);					}catch(Exception e){			e.printStackTrace();			return null;		}finally{						if(hpc != null)				try {					hpc.close();				} catch (IOException e) {					// TODO Auto-generated catch block					e.printStackTrace();				}			if(dis != null)				try {					dis.close();				} catch (IOException e) {					// TODO Auto-generated catch block					e.printStackTrace();				}		}			}					public void commandAction(Command c, Displayable arg1) {		if(c==exitCommand){			this.notifyDestroyed();		}	}			}


wap.txt内容如下:
Jerry is test the server