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

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值