Reading Files in Android (From Application Resources)

40 sec read

Android Development

Dear readers

Android provides different types of storage for application data. Broadly they can be categorised as

  1. File Storage
  2. DB Storage
  3. Network Storage

File Storage can then be further classified as Internal And External. Moreover few files can be bundled and compiled with application itself. [ but definitely doing this will increase size of resultant apk].

Here in this article we will be reading a file from our application resources  and then we will be displaying data through it inside our application.  Below is the code to read a text file line by line from raw directory of application resources.

 

public String getData(String filename) {
StringBuffer resultAllFile = new StringBuffer();
InputStream ins = getResources().openRawResource(
        getResources().getIdentifier(filename,
                "raw", getPackageName()));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ins));

String line = "";

try {
    while ((line = bufferedReader.readLine()) != null) {
        resultAllFile.append(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
return resultAllFile.toString();
}

 

But remember call this method on worker thread so that your UIThread will remain free to show those stunning animations you are thinking of.

Below is demo video for the blog to see all this in action