How can I read a text file from the SD card in Android?
In your layout you'll need something to display the text. A TextView
is the obvious choice. So you'll have something like this:
<TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="fill_parent"/>
And your code will look like this:
//Find the directory for the SD Card using the API//*Don't* hardcode "/sdcard"File sdcard = Environment.getExternalStorageDirectory();//Get the text fileFile file = new File(sdcard,"file.txt");//Read text from fileStringBuilder text = new StringBuilder();try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close();}catch (IOException e) { //You'll need to add proper error handling here}//Find the view by its idTextView tv = (TextView)findViewById(R.id.text_view);//Set the texttv.setText(text);
This could go in the onCreate()
method of your Activity
, or somewhere else depending on just what it is you want to do.
In response to
Don't hardcode /sdcard/
Sometimes we HAVE TO hardcode it as in some phone models the API method returns the internal phone memory.
Known types: HTC One X and Samsung S3.
Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android
You should have READ_EXTERNAL_STORAGE permission for reading sdcard.Add permission in manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this linkPermissions overview
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0); }}