1. Use any XML Resource
The XML file to be read is stored in the/RES/XML subdirectory.
For example:/RES/XML/test. xml
<rootelem1><subelem1>Hello World</subelem1></rootelem1>
Read XML files:
Resources res = activity.getResources();XmlResourceParser xpp = res.getXml(R.xml.test);
Use xmlpullparser:
private String getEventsFromXMLFile(Activity activity) throws XmlPullParserException, IOException{StringBuffer sb = new StringBuffer();Resources res = activity.getResources();XmlResourceParser xpp = res.getXml(R.xml.test);xpp.next();int eventType = xpp.getEventType();while(eventType != XmlPullParser.END_DOCUMENT){if(eventType == XmlPullParser.START_DOCUMENT){sb.append("**Start document");}else if(eventType == XmlPullParser.START_TAG){sb.append("\nStart tag "+xpp.getName());}else if(eventType == XmlPullParser.END_TAG){sb.append("\nEnd tag "+xpp.getName());}else if(eventType == XmlPullParser.TEXT){sb.append("\nText "+xpp.getText());}eventType = xpp.next();}sb.append("\n**End document");return sb.toString();}
2. Use Original Resources
Raw resources are located in/RES/raw. These resources are not compiled and transferred to the application package as they are.
For example:/RES/raw/test.txt
Read Original Resources:
String getStringFromRawFile(Activity activity) throws IOException{Resources r = activity.getResources();InputStream is = r.openRawResource(R.raw.test);ByteArrayOutputStream baos = new ByteArrayOutputStream();int i = is.read();while(i != -1){baos.write(i);i = is.read();}String myText = baos.toString();is.close();return myText;}
3. Assets used
/Assets are not included in the/RES file, so files in the asset do not generate R. resource ID in Java. You must specify the file path to read them. The file path is the relative path starting with/assets.
You can use the assetmanager class to access these files.
AssetManager am = activity.getAssets();InputStream is = am.open("test.txt");