欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-24 11:29:04
...
J2ME下载并读取服务器txt文件,我用的公司的服务器,大家如果测试代码需要修改为自己的url,本实例是将服务器的txt文件内容添加到TextField显示,当然也可以保存到RMS中,代码如下:

[img]http://dl.iteye.com/upload/attachment/212025/4d1928f4-13a9-3401-9f37-60774f366fd1.png[/img]




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();
}
}




}




[color=green]wap.txt内容如下:[/color]

Jerry is test the server

上一篇: 前端直接导出excel

下一篇: J2ME