Friday 4 October 2019

Post 76: Read from local resource in Android

In this post I'll show you how to read from local resource in Android. In this case it's a text file "text_file.txt" in the folder "raw" under the "res" folder.

private final Context helperContext = this; // put this on top of your class
....

final Resources resources = helperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.text_file);

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

try {
    String line = "";
    while ((line = reader.readLine()) != null) {
       System.out.println(line);
       // do something..., e.g. add in to an ArrayList
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

No comments:

Post a Comment

Tweet