Android: Can't read from file using FileInputStream

I am trying to read from a file named "quiz_questions.txt" in my res / raw folder. The code I'm compiling, but it looks like it stops before it hits the FileInputStream. It might open it up but not read 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();
        }
    }
}
}

      

+3


source to share


1 answer


You are not posting it, but I am assuming you are getting a NullPointerException. This is due to what con

is null

when you try to create FileInputStream

.

Just remove con

from instructions.

FileInputStream fis = (FileInputStream) getResources().openRawResource(
    R.raw.quiz_questions);

      



You must refactor your code as well, so it fis

closes regardless of whether an exception is thrown:

public void fillArray() {
    InputStream fis = null;
    try {
        fis = 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;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fis != null) {
            try { fis.close(); }
            catch (IOException ignored) {}
        }
    }
}

      

+3


source







All Articles