Android reads txt files from assets and raw and androidassets
Method 1. Copy the txt file to be read to the assets folder under the Android project directory.
Method 2: Create a raw folder in the res folder and copy the txt file to the directory.
This method reads data from assets.
/*** Read txt from assets */private void readFromAssets () {try {InputStream is = getAssets (). open ("qq.txt"); String text = readTextFromSDcard (is); textView. setText (text);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}
This method reads data from raw.
/*** Read txt from raw */private void readFromRaw () {try {InputStream is = getResources (). openRawResource (R. raw. qq); String text = readTextFromSDcard (is); textView. setText (text);} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}
This method parses the input stream and returns the string in the txt file.
/*** Read txt by line ** @ param is * @ return * @ throws Exception */private String readTextFromSDcard (InputStream is) throws Exception {InputStreamReader reader = new InputStreamReader (is); BufferedReader bufferedReader = new BufferedReader (reader); StringBuffer buffer = new StringBuffer (""); String str; while (str = bufferedReader. readLine ())! = Null) {buffer. append (str); buffer. append ("\ n");} return buffer. toString ();}