j2me文件读入
天地一棵树 2011-04-02 08:21:41 我在写一个手机上的文本阅读器,想从文件读入文本,然后显示在手机屏幕上,但是老是显示不了,这个怎么弄,关于文件存放的位置和读入是应该写什么路径,请各位大虾指导一下
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();
}
}
}