Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art
Reading a File Shipped with the App Rather Than in the FilesystemBack to Android Cookbook Home | Up to Chapter: Data Persistence

Author: Rachee Singh ('racheesingh')
In Published Edition? Yes
FormatLanguage: WikiFormat

Reading a File Shipped with the App Rather Than in the Filesystem

Problem

You need to access data stored in a file in /res/raw directory.

Solution

Using the getResources() and openRawResource() method to read from the sample file.

Discussion

We wish to read information from a file in the android application. So we will require to put the relevant file in the res/raw directory (we need to create the directory since it is not present by default). Then using the InputStreamReader and BufferedReader, we will read the file. Then we extract the String from the BufferedReader using the readLine method. Eclipse asks to enclose the readLine function within a try-catch block since there is a possibility of it throwing anIOException.

The file included in /res/raw is named 'samplefile'.

InputStreamReader is = new InputStreamReader(this.getResources().openRawResource(R.raw.samplefile));
BufferedReader reader = new BufferedReader(is);
StringBuilder finalText = new StringBuilder();
String line;
try {
	while ((line = reader.readLine()) != null) {
	    finalText.append(line);
	}
} catch (IOException e) {
	e.printStackTrace();
}
fileTextView = (TextView)findViewById(R.id.fileText);
fileTextView.setText(finalText.toString());

After reading the entire string, we set it to the TextView in the activity.

See Also

Download

https://docs.google.com/leaf?id=0B_rESQKgad5LMWJjYjQwMjYtNDVlMi00Y2M5LTk1MmItMTc3OGNhNWZiNjNh&hl=en_US