Textscreen in Codename One, how to read text file?

╄→尐↘猪︶ㄣ 提交于 2019-12-06 02:50:43

In the Codename One Designer go to the data section and add a file.

You can just add the text there and fetch it using myResFile.getData("name");.

You can also store the file within the src directory and get it using Display.getInstance().getResourceAsStream("/filename.txt");

I prefer to have the text file in the filesystem instead of the resource editor, because I can just edit the text with the IDE. The method getResourceAsStream is the first part of the solution. The second part is to load the text in one go. There was no support for this in J2ME, you needed to read, handle buffers etc. yourself. Fortunately there is a utility method in codename one. So my working method now looks like this:

    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";
        }
    }

The following code worked for me.

//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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!