/res 目錄。.txt,支援多段落、保留空白符號。private String readChapter(String resPath) {
InputStream is = null;
ByteArrayOutputStream bos = null;
try {
is = getClass().getResourceAsStream(resPath);
bos = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1) bos.write(ch);
return bos.toString().trim();
} catch (IOException e) {
e.printStackTrace(); return "載入失敗:" + e.getMessage();
} finally {
try { if (is != null) is.close(); } catch (IOException ignored) {}
try { if (bos != null) bos.close(); } catch (IOException ignored) {}
}
}
private List mainMenu;
private Command cmdExit = new Command("離開", Command.EXIT, 1);
private void showMainMenu() {
mainMenu = new List("文本閱讀器", Choice.IMPLICIT);
mainMenu.append("第一章", null);
mainMenu.append("第二章", null);
mainMenu.append("第三章", null);
mainMenu.addCommand(cmdExit);
mainMenu.setCommandListener(this);
display.setCurrent(mainMenu);
}
private Command cmdBack = new Command("返回", Command.BACK, 1);
private void showChapter(int index) {
String[] files = {"/res/ch1.txt","/res/ch2.txt","/res/ch3.txt"};
String content = readChapter(files[index]);
Form form = new Form("第 " + (index+1) + " 章");
form.append(content);
form.addCommand(cmdBack);
form.setCommandListener(this);
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) { destroyApp(false); notifyDestroyed(); }
else if (c == cmdBack) { showMainMenu(); }
else if (d == mainMenu) {
showChapter(mainMenu.getSelectedIndex());
}
}
public class ReaderMIDlet extends MIDlet implements CommandListener {
private Display display;
// ... 欄位、建構子、startApp/pauseApp/destroyApp
protected void startApp() { if (display == null) { display = Display.getDisplay(this); showMainMenu(); } }
// commandAction 如上
}
form.append()。String.indexOf() 關鍵字高亮(需 Canvas 繪製)。src/ReaderMIDlet.java、res/ch1.txt、res/ch2.txt、res/ch3.txt。res。以 List+Form 快速建構雙層導航,配合資源檔讀取工具,即可在數小時內完成功能完整的 J2ME 文本閱讀器,適合電子書、教材、說明書等離線閱讀場景。