Android:无法使用FileInputStream从文件读取

时间:2012-03-25 21:14:16

标签: java android fileinputstream

我正在尝试读取res / raw文件夹中名为“quiz_questions.txt”的文件。我编译的代码,但看起来它在到达FileInputStream之前就停止了。也许是打开它,但不是读它。我不确定。

import java.io.*;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;

public class Questions extends Activity {

public String[][] questions = new String[10][5];

public void fillArray() {
    {
        Context con = null;
        try {
            //fis = new BufferedInputStream(new FileInputStream("res/raw/quiz_questions.txt"));
            FileInputStream fis = (FileInputStream) con.getResources().openRawResource(R.raw.quiz_questions);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            String nextLine;
            int i = 0, j = 0;
            while ((nextLine = br.readLine()) != null) {
                if (j == 5) {
                    j = 0;
                    i++;
                }
                questions[i][j] = nextLine;
            }
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
}

1 个答案:

答案 0 :(得分:5)

你没有发布它,但我想你得到的是NullPointerException。这是因为当您尝试创建con时,nullFileInputStream

由于Activity已经是Context,您可以从声明中删除con。 (您还应该使用InputStream界面而不是FileInputStream。)

InputStream is = getResources().openRawResource(R.raw.quiz_questions);

最后,您应该重新组织代码,以便关闭is,无论是否抛出异常:

public void fillArray() {
    try (InputStream is = getResources().openRawResource(R.raw.quiz_questions)) {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String nextLine;
        int i = 0, j = 0;
        while ((nextLine = br.readLine()) != null) {
            if (j == 5) {
                j = 0;
                i++;
            }
            questions[i][j] = nextLine;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}