简体   繁体   English

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

[英]Android: Can't Read From File using FileInputStream

I'm trying to read from a file called "quiz_questions.txt" in my res/raw folder. 我正在尝试从res / raw文件夹中的一个名为“quiz_questions.txt”的文件中读取。 The code I have compiles, but it looks like it stops before it gets to the FileInputStream. 我编译的代码,但看起来它在到达FileInputStream之前就停止了。 Maybe it is opening it, but not reading it. 也许是打开它,但不是读它。 I'm not sure. 我不确定。

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();
        }
    }
}
}

You don't post it, but I imagine that you are getting a NullPointerException. 你不发布它,但我想你得到一个NullPointerException。 This is because con is null when you try to create the FileInputStream . 这是因为当您尝试创建FileInputStreamconnull

Since an Activity is already a Context , you can just eliminate con from the statement. 由于Activity已经是Context ,因此您可以从语句中删除con (You should also use the InputStream interface instead of FileInputStream .) (您还应该使用InputStream接口而不是FileInputStream 。)

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

Finally, you should reorganize your code so is is closed whether or not an exception is thrown: 最后,你应该重新组织你的代码,这样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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM