本源代码包括J2ME开发精解 该书的全部章节的示例代码
源代码在线查看: filecontroller.java
package com.j2medev.ch8.fc;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.*;
/**
*
* @author Administrator
*/
public class FileController implements CommandListener{
private PowerAudio midlet = null;
private Display display = null;
private Image dirImg = null;
private Image fileImg = null;
private String currentDir = null;//存储当前目录
public static final String UP_DIR = "返回上级目录";
public static final String ROOT = "/";
public static final String SEPARATOR_STR = "/";
public static final char SEPARATOR = '/';
public static final Command exitCommand = new Command("退出",Command.OK,1);
public FileController(PowerAudio midlet) {
this.midlet = midlet;
currentDir = ROOT;
if(display == null){
display = Display.getDisplay(midlet);
}
try{
dirImg = Image.createImage("/dir.png");
fileImg = Image.createImage("/file.png");
}catch(IOException ex){
ex.printStackTrace();
}
}
public void setCurrent(Displayable displayable){
display.setCurrent(displayable);
}
public void showCurrentDir(){
List main = new List(currentDir,List.IMPLICIT);
Enumeration enums = null;
FileConnection fc = null;
try{
//当前目录为根目录
if(currentDir.equals(ROOT)){
enums = FileSystemRegistry.listRoots();
}else{
main.append(UP_DIR, dirImg);
fc = (FileConnection)Connector.open("file://"+currentDir);
enums = fc.list();
}
while(enums.hasMoreElements()){
String obj = (String)enums.nextElement();
if(obj.charAt(obj.length()-1)==SEPARATOR){
//目录结构
main.append(obj, dirImg);
}else{
//文件
main.append(obj, fileImg);
}
}
if(fc != null){
fc.close();
}
main.addCommand(exitCommand);
main.setCommandListener(this);
display.setCurrent(main);
}catch(IOException ex){
ex.printStackTrace();
}
}
public void tranverse(String fileName){
if(fileName.equals(UP_DIR)){
int i = currentDir.lastIndexOf(SEPARATOR, currentDir.length()-2);
if(i != -1){
currentDir = currentDir.substring(0, i+1);
}else{
currentDir = ROOT;
}
}else{
currentDir = currentDir + fileName;
}
showCurrentDir();
}
public void play(String fileName){
if(!fileName.endsWith("mid")){
return;
}
String file = "file://"+currentDir+fileName;
FileConnection fc = null;
try{
fc = (FileConnection)Connector.open(file);
InputStream is = fc.openInputStream();
if(is != null){
AudioPlayer player = new AudioPlayer(this);
player.initVideo(is, fileName);
}
}catch(IOException ex){
ex.printStackTrace();
}
}
public void commandAction(Command cmd,Displayable displayable){
if(cmd == List.SELECT_COMMAND){
List list = (List)displayable;
String fileName = list.getString(list.getSelectedIndex());
if(fileName.endsWith(SEPARATOR_STR) || fileName.equals(UP_DIR)){
tranverse(fileName);
}else{
play(fileName);
}
}else if(cmd == exitCommand){
midlet.exit();
}
}
}