Android reads txt files from assets and raw and androidassets

Source: Internet
Author: User

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 ();}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.