我正在尝试读取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();
}
}
}
}
答案 0 :(得分:5)
你没有发布它,但我想你得到的是NullPointerException。这是因为当您尝试创建con
时,null
为FileInputStream
。
由于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();
}
}