天地一棵树 2011年04月02日
j2me文件读入
我在写一个手机上的文本阅读器,想从文件读入文本,然后显示在手机屏幕上,但是老是显示不了,这个怎么弄,关于文件存放的位置和读入是应该写什么路径,请各位大虾指导一下
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
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.Image;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;


public class Reader extends MIDlet implements CommandListener{

//currentdir
private String currentDir="file:///shanliangsishen.txt";
private Command readCommand=new Command("Read",Command.ITEM,1);
// exitcommand
private Command exitCommand=new Command("Exit",Command.EXIT,1);
private String fileName="shanliangsishen.txt";

private Form form;
private Display display;
private String currentPath;


public Reader() {
// TODO Auto-generated constructor stub
form=new Form("Read");
display=Display.getDisplay(this);
currentPath=System.getProperty(currentDir);


}

protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub

}

protected void pauseApp() {
// TODO Auto-generated method stub

}

protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
form.addCommand(readCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);

}

//readFile
private void readFile(){
FileConnection fc=null;
InputStream dis=null;
try{
fc=(FileConnection)Connector.open(currentPath+fileName,Connector.READ_WRITE);
dis=fc.openInputStream();
int size=dis.available();
byte[] data=new byte[size];
dis.read(data);
String fileContent=new String(data);
form.append(fileContent);
// display.setCurrent(form);

}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(fc!=null){
fc.close();
fc=null;
}
if(dis!=null){
dis.close();
dis=null;
}

}catch(Exception e){
e.printStackTrace();
}
}
}
public void commandAction(Command c, Displayable d) {
// TODO Auto-generated method stub
if(c==readCommand){
readFile();
// form.setCommandListener(this);
// display.setCurrent(form);
display.setCurrent(form);
}else if(c==exitCommand){
notifyDestroyed();
}

}
}
...全文
26 点赞 收藏 5
写回复
5 条回复

还没有回复,快来抢沙发~

发动态
发帖子
嵌入开发(WinCE)
创建于2007-09-28

8162

社区成员

4.1w+

社区内容

硬件/嵌入开发 嵌入开发(WinCE)
社区公告
暂无公告