Working with Raw Resources

Android also allows raw files in addition to raw XML files. These raw resources, placed in /res/ raw, are arbitrary file resources such as audio, video, or text files that require localization or references through resource IDs. Unlike the raw XML files placed in /res/xml, these files are not compiled but moved to the application package as is. However, each file will have an identifier generated in R.java. If you were to place a text file at /res/raw/test.txt, you would be able to read that file using the code in Listing 3-19.

Listing 3-19. Reading a Raw Resource

String getStringFromRawFile(Activity activity) {

Resources r = activity.getResources(); InputStream is = r.openRawResource(R.raw.test); String myText = convertStreamToString(is); is.close(); return myText;

String convertStreamToString(InputStream is) {

ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = is.read();

return baos.toString();

0 0

Post a comment