在Codename One中的Textscreen,如何阅读文本文件?

我想在我的Codename One App中添加一个帮助屏幕。 由于文本比其他字符串更长,我想将它放在一个单独的文件中并将其添加到app-package中。

我该怎么做呢? 我在哪里放置文本文件,如何轻松地将其读入字符串?

(我已经知道如何将字符串放入表单内的文本区域)

在Codename One Designer中,转到数据部分并添加文件。

你可以在那里添加文本并使用myResFile.getData("name");获取它myResFile.getData("name");

您还可以将文件存储在src目录中,并使用Display.getInstance().getResourceAsStream("/filename.txt");获取它Display.getInstance().getResourceAsStream("/filename.txt");

我更喜欢在文件系统而不是资源编辑器中使用文本文件,因为我可以使用IDE编辑文本。 getResourceAsStream方法是解决方案的第一部分。 第二部分是一次加载文本。 在J2ME中没有对此的支持,您需要自己阅读,处理缓冲区等。 幸运的是,有一种代号为1的实用方法。 所以我的工作方法现在看起来像这样:

  final String HelpTextFile = "/helptext.txt"; ... InputStream in = Display.getInstance().getResourceAsStream( Form.class, HelpTextFile); if (in != null){ try { text = com.codename1.io.Util.readToString(in); in.close(); } catch (IOException ex) { System.out.println(ex); text = "Read Error"; } } 

以下代码对我有用。

 //Gets a file system storage instance FileSystemStorage inst = FileSystemStorage.getInstance(); //Gets CN1 home` final String homePath = inst.getAppHomePath(); final char sep = inst.getFileSystemSeparator(); // Getting input stream of the file InputStream is = inst.openInputStream(homePath + sep + "MyText.txt"); // CN1 Util class, readInputStream() returns byte array byte[] b = Util.readInputStream(is); String myString = new String(b);