2

我正在阅读 Mario Zechner 的“Beginning Android Games”一书,我很高兴我拿起了它,但我现在遇到了一个问题,他要求用户在本书的早期编写代码。并不是说我反对对它们进行编码,我宁愿知道自己在做什么,也不愿做一个半吊子的工作,而且当我走得更远时,它不会很好地工作。

所以 AssetManager 似乎不想加载我的文件。

    AssetManager am = getAssets();
    InputStream inputStream = null;
    try {
        am.open("assets/texts/hello.txt");
        String text = loadTextFile(inputStream);
        tv.setText(text);
    } catch (IOException e) {
        tv.setText("Could not Load file");
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                tv.setText("Could not close file");
            }
        }
    }
}

按照所有标准,我应该能够只使用链接:“texts/hello.txt”,但每次我这样做时都会向我射击 NPE。所以我被迫使用完整链接。使用完整链接允许程序运行它只是无法按照它告诉我“无法加载文件”的说明加载我的文本文档

我想我现在会把这个问题扼杀在萌芽状态,这样它就不会成为以后的主要问题。

4

2 回答 2

2

将您的代码更改为:

 AssetManager am = getAssets();
    InputStream inputStream = null;
    try {

         inputStream= am.open("texts/hello.txt"); //<<<<
        String text = loadTextFile(inputStream);
        tv.setText(text);
    } catch (IOException e) {

    // your code here

因为您将 null 传递inputStreamloadTextFile方法

于 2013-01-25T17:08:46.440 回答
0
// To load text file
        InputStream input;
        try {
          input = assetManager.open("helloworld.txt");

             int size = input.available();
             byte[] buffer = new byte[size];
             input.read(buffer);
             input.close();

             // byte buffer into a string
             String text = new String(buffer);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
于 2013-01-25T17:19:47.807 回答