Android: Read a text file from resources


/ Published in: Java
Save to your folder(s)

put your text files into the res/raw folder.


Copy this code and paste it in your HTML
  1. static public String readStringFromResource(Context ctx, int resourceID) {
  2. StringBuilder contents = new StringBuilder();
  3. String sep = System.getProperty("line.separator");
  4.  
  5. try {
  6. InputStream is = ctx.getResources().openRawResource(R.raw.trails);
  7.  
  8. BufferedReader input = new BufferedReader(new InputStreamReader(is), 1024*8);
  9. try {
  10. String line = null;
  11. while (( line = input.readLine()) != null){
  12. contents.append(line);
  13. contents.append(sep);
  14. }
  15. }
  16. finally {
  17. input.close();
  18. }
  19. }
  20. catch (FileNotFoundException ex) {
  21. Log.e(TAG, "Couldn't find the file " + resourceID + " " + ex);
  22. return null;
  23. }
  24. catch (IOException ex){
  25. Log.e(TAG, "Error reading file " + resourceID + " " + ex);
  26. return null;
  27. }
  28.  
  29. return contents.toString();
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.