Reading and Writing a file to SD card sample program in Android

By: Ashley Emailed: 1607 times Printed: 2074 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

This sample android program shows you how write and read a file from SD Card in Android. In this program four buttons are shown and a Edit box. When you type some text into the edit box and click, Save to SD Card button, the text is saved to a text file and saved to the SD Card. When you click clear button, the edit box contents are cleared. When you click, Read Sd card button the file is read from the SD card and the contents are copied to the edit box. 

The FileDemo2.java file is as follows:

package com.javasamples;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class FileDemo2 extends Activity {
	// GUI controls
	EditText txtData;
	Button btnWriteSDFile;
	Button btnReadSDFile;
	Button btnClearScreen;
	Button btnClose;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
	// bind GUI elements with local controls
	txtData = (EditText) findViewById(R.id.txtData);
	txtData.setHint("Enter some lines of data here...");

	btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
	btnWriteSDFile.setOnClickListener(new OnClickListener() {

	public void onClick(View v) {
		// write on SD card file data in the text box
		try {
			File myFile = new File("/sdcard/mysdfile.txt");
			myFile.createNewFile();
			FileOutputStream fOut = new FileOutputStream(myFile);
			OutputStreamWriter myOutWriter = 
									new OutputStreamWriter(fOut);
			myOutWriter.append(txtData.getText());
			myOutWriter.close();
			fOut.close();
			Toast.makeText(getBaseContext(),
					"Done writing SD 'mysdfile.txt'",
					Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), e.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
	}// onClick
	}); // btnWriteSDFile

		btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
		btnReadSDFile.setOnClickListener(new OnClickListener() {

		public void onClick(View v) {
			// write on SD card file data in the text box
		try {
			File myFile = new File("/sdcard/mysdfile.txt");
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(
					new InputStreamReader(fIn));
			String aDataRow = "";
			String aBuffer = "";
			while ((aDataRow = myReader.readLine()) != null) {
				aBuffer += aDataRow + "\n";
			}
			txtData.setText(aBuffer);
			myReader.close();
			Toast.makeText(getBaseContext(),
					"Done reading SD 'mysdfile.txt'",
					Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			Toast.makeText(getBaseContext(), e.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
		}// onClick
		}); // btnReadSDFile

		btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
		btnClearScreen.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// clear text box
				txtData.setText("");
			}
		}); // btnClearScreen

		btnClose = (Button) findViewById(R.id.btnClose);
		btnClose.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// clear text box
				finish();
			}
		}); // btnClose

	}// onCreate

}// AndSDcard


The output of this program will be as shown in the android emulator below.

The main.xml file in your res/layout folder is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000ff"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<EditText
android:id="@+id/txtData"
android:layout_width="fill_parent"
android:layout_height="180px"
android:textSize="18sp"  />

<Button
android:id="@+id/btnWriteSDFile"
android:layout_width="143px"
android:layout_height="44px"
android:text="1. Write SD File"  />

<Button
android:id="@+id/btnClearScreen"
android:layout_width="141px"
android:layout_height="42px"
android:text="2. Clear Screen"  />

<Button
android:id="@+id/btnReadSDFile"
android:layout_width="140px"
android:layout_height="42px"
android:text="3. Read SD File"  />

<Button
android:id="@+id/btnClose"
android:layout_width="141px"
android:layout_height="43px"
android:text="4. Close" />

</LinearLayout>




Android Home | All Android Tutorials | Latest Android Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(53)


1. View Comment

I get the exception with the message "Permission denied" when I try to write the file. This is in the Eclipse dev environment. Any ideas how I can enable my app to write simple data to the android file system ?

View Tutorial          By: Jan at 2011-07-20 08:58:55
2. View Comment

In your AndroidManifest.xml file you will have to provide the permision (android.permission.WRITE_EXTERNAL_STORAGE)

Eg.

<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
</manifest>


View Tutorial          By: Ashley at 2011-07-21 02:47:49
3. View Comment

I made this "In your AndroidManifest.xml file you will have to provide the permision (android.permission.WRITE_EXTERNAL_STORAGE)"

Still not working, toasts "Permission denied" /:


View Tutorial          By: lalo at 2011-11-20 05:56:43
4. View Comment

I am getting error in setContentView(R.layout.main);

it is saying main cannot be resolved or is not a field
can someone help this out


View Tutorial          By: user at 2012-01-13 06:49:42
5. View Comment

good one

View Tutorial          By: saurabh at 2012-01-17 04:43:29
6. View Comment

</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
</manifest>

put that permission at the specified position as described above
i hope u will get relieved.


View Tutorial          By: saurabh at 2012-01-17 05:00:21
7. View Comment

nice its working good example.... very useful...

View Tutorial          By: Mamatha at 2012-02-02 09:23:40
8. View Comment

i am getting a force close...can anyone please help me...

View Tutorial          By: jack at 2012-03-22 15:18:37
9. View Comment

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try this at Menifest


View Tutorial          By: Dev at 2012-04-06 06:19:03
10. View Comment

Hi am saving data in to the internal memory.But how can i move the db data in to SD-card and where i can change the modifications please help me.
so many links are there but i can't understand where i can put the code.
In Advance Thanks.


View Tutorial          By: harsha at 2012-04-27 07:48:45
11. View Comment

Hi, still having problem with 'Permission denied'...

Manifest is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test2.test"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" android:debuggable="true">
<activity
android:name=".Test2Activity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>


View Tutorial          By: Dorjoo at 2012-05-18 19:00:22
12. View Comment

Good Tutorial.
Thanks.


View Tutorial          By: Oki Wicaksono at 2012-05-29 04:09:05
13. View Comment

what if i want to create a digital signature on the android and keep it on sdcard ..
anyone can help me?


View Tutorial          By: Chandra at 2012-06-10 00:52:15
14. View Comment

Thank You , It's Very Good.

View Tutorial          By: Jack at 2012-06-10 14:09:24
15. View Comment

gud tutorial but the permission denied is because of two things,,
1 in android manifest file user havnt added write external storage permisison

2 sdcard is not mounted so user can check it
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
}

so first mount sdcard :)


View Tutorial          By: amithooda at 2012-06-11 06:43:00
16. View Comment

Wow, damn nice. It does everything, and the script is meticulous and instructive. If you only add the step of setting uses-permission in the Manifest, you'll have all bases covered, and readers' snags will cease. The hunt for working code was getting long and fruitless -- thanks. [Readers with problems, follow the tag in comments 2 and 6, while even briefer is end-tag-less form in comment 11.]

View Tutorial          By: Ethan Windsor at 2012-06-14 13:47:39
17. View Comment

When I use this code it puts everything I append onto one line. Is there anyway to make it so that when I append something it appends to the next line of the text file?

View Tutorial          By: Amber at 2012-06-18 15:33:22
18. View Comment

How do u edit the text ? this is always replacing the text present

View Tutorial          By: anurag at 2012-08-23 07:24:47
19. View Comment

Its working ,but it overwrite the old one when run again ,i need to save a file in separate text (just like notepad saving)

View Tutorial          By: venkat at 2012-09-17 09:38:53
20. View Comment

I have no mounted the sd card, and I have the "Permission denied" error. How can I mount the sd card??

View Tutorial          By: Cgamboa at 2012-12-01 06:39:14
21. View Comment

thanks! great tutorial!

View Tutorial          By: Gracia at 2013-01-10 07:58:06
22. View Comment

dude its forces closes everytime what to do .....help me

View Tutorial          By: raam at 2013-01-10 13:05:57
23. View Comment

my program is run and it created file in the sd card but problem is that only one string is write in the file.So how can write multiple strings in file?
and how to compare string with that multiple string and shows the matched string.....


View Tutorial          By: mahesh at 2013-01-21 04:15:21
24. View Comment

i want to open pdf file from sd card and i dont want to use any external viewer for this how can i do this?

thanks for giving me your time...


View Tutorial          By: Karan Mavadhiya at 2013-01-30 12:02:30
25. View Comment

Great tutorial. Working absolutely fine. I needed to implement this kind of "writing in to SD Card". However in my case, I wanted to "prompt" the user to select a file name and location for saving the editText content. Can you help me in this?
Please mail me.


View Tutorial          By: Ashwin at 2013-02-28 21:45:29
26. View Comment

Hi i changed some codes in that and i gave internet permission to manifest. But I have a problem. when I click the write button I cannot change my xml file on my host with this sample. could u help me please. Error is: open failed: EROFS(Read-only file system)

I changes so:
try {
URL url = new URL("http://22net.edirnesaglik.gov.tr/deneme/data.xml");

File myFile = new File("url.openStream()");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);


Thank You =)


View Tutorial          By: Göktuğ ÖZEL at 2013-03-13 22:44:55
27. View Comment

Good one......
Thanks.


View Tutorial          By: Suresh at 2013-03-14 07:38:45
28. View Comment

superb its working perfect but one thing, we have to add a permission in manifest file for creating a file in SD card.
here the line : <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> copy and paste the line in manifest file...!


View Tutorial          By: venkatachalam at 2013-03-14 16:35:00
29. View Comment

Thank you, very useful example!

View Tutorial          By: Hui Chun Wai at 2013-03-24 15:07:53
30. View Comment

How to delete file button

View Tutorial          By: Chinzoo at 2013-04-13 13:30:18
31. View Comment

Thank you, saved my life

View Tutorial          By: Zs at 2013-04-13 22:51:54
32. View Comment

i added respective code to the Manifest in every conceivable shape and form. i still get the error

OPEN FAILED : EACCS Permission denied

so i guess i have to mount the sdcard. how exactly do i do that though?


View Tutorial          By: niko at 2013-04-19 18:23:41
33. View Comment

also MEGA IMPORTANT:

make sure you actually have an sd card implemented in your virtual device!!!


DUHHHHHH!!!!


View Tutorial          By: niko at 2013-04-19 18:55:14
34. View Comment

Thanks.It helps a lot to me.

View Tutorial          By: Sachin at 2013-05-24 19:36:36
35. View Comment

Hi All........
People those who are getting error like "Permission Denied" just follow this below text.............

1. First of all you need to provide the permission (android.permission.WRITE_EXTERNAL_STORAGE) at your androidmanifest.xml file.

2. If you are getting the same error then go to the AVD manager at eclipse IDE and

2(a). Select a particular AVD and click the edit button

2(b). And provide the SD Card size as per your necessity and run your program with the AVD..........

Hope it will work for you guys...........


View Tutorial          By: Abhijit at 2013-05-28 11:24:24
36. View Comment

Thanks For This Explanatory Tutorial .

View Tutorial          By: Pralay at 2013-06-15 03:50:26
37. View Comment

I am getting error in setContentView(R.layout.main);

it is saying main cannot be resolved or is not a field
can someone help this out


View Tutorial          By: Malick at 2013-06-30 06:57:30
38. View Comment

Hi,,i try this tutorial,,it working,,but it kind of different from what i want,,i want ti write in external storage such as our micro sd,,but this tutorial keep saving into internal storage,,can someone help me?
Thank you.


View Tutorial          By: Eka Praditya at 2013-07-02 04:11:41
39. View Comment

thnx for the nice tutorial. but i need to create a diray app where the text of every day should be saved to sd card separately and can be read from sd card by a specific chosen date. plz someone help me in this

View Tutorial          By: sharath at 2013-09-07 16:29:19
40. View Comment

Thanks a lot for this nice tutorial, it is very helpful! But I have a question. Is there also a way to create a new folder with the file in it by clicking the "Write SD file" button? For example, " /sdcard/myfolder/mysdfile.txt"

View Tutorial          By: Ted at 2014-02-07 12:50:24
41. View Comment

hi its working nice,can u plz help me how to fetch the coordinates from GPS and write it to Text file in SD card.

View Tutorial          By: Manju gowda at 2014-02-21 07:23:44
42. View Comment

How can i read PDF files from external memory(SD card) card?

View Tutorial          By: Aswanth at 2014-03-31 09:46:26
43. View Comment

im trying to just store the data taken from editext fields in text file. Everythings works well and fine but the problem is im getting encrypted values in the file in sd card. anyone pls help me asap. i want to use the file stored in sd card for mailing.

View Tutorial          By: praveen at 2014-08-05 15:19:51
44. View Comment

thanx mitra...it helped alot.

View Tutorial          By: psuyog at 2014-10-10 12:16:26
45. View Comment

where is mysdfile.txt file created. where can i find it.

View Tutorial          By: Venkatesh at 2014-11-12 10:53:52
46. View Comment

Hi, I cant open the file after I click Write SD. It is giving the error message "No such files or directory" Help Please. thank u

View Tutorial          By: hassan at 2014-12-17 07:44:16
47. View Comment

Working !

Nice example, thanks !


View Tutorial          By: Akh at 2015-01-14 14:22:24
48. View Comment

I need one help how to update particular column data only in csv file using android source code

View Tutorial          By: santhosh.s at 2015-01-22 15:09:33
49. View Comment

How could i read a file from my ftp server . suggest me relevent codes or send me any links.

View Tutorial          By: Dinshaw at 2015-02-06 07:22:03
50. View Comment

Thanks guys,
its working perfectly.
Now, what do i have to do if i want to add more data to the text file. i want to add the next set of data to the next line and not overwrite. Please help.
thanks


View Tutorial          By: Ajmal at 2015-03-25 08:30:07
51. View Comment

Not able to store on SD card.But storing on phone storage.

View Tutorial          By: kusuma at 2015-07-25 13:42:17
52. View Comment

this text is overlapping the existing text what if i want to see a list of text like both the existing and new text can u please help me....

View Tutorial          By: Alda at 2015-10-02 18:22:22
53. View Comment

I have altered the code as described (xml addition) but I still get a write error on writing the file. I have added the mount check and also placed a toast message which shows de path of the SDcard on my testdevice /storage/sdcard so I'm pretty shore it's mounted.
EACCESS (permission denied)

Then I looked again and saw I placed the lines in the manifest within the application tags... they have to be placed outside. This changed things for the better... thanks for the fine example.


View Tutorial          By: Spijker at 2015-10-14 12:27:47

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Ashley
Is autodiscover CNAME a must in Office 365
Directory Synchronization tool in Office 365
Configure Outlook Manually for Office 365
Review: Ruggear - The world's most Rugged Phone in Singapore
Solution to error: unable to open connection to server due to security error
Making your Alias email as 'Send As' in Office 365
Steps to Create Shared Mailbox in office 365
xxxx cannot be loaded because the execution of scripts is disabled on this system. Please see “get-help about_signing” for more details.
The user's Outlook Live mailbox is full.
Outlook Live couldn't connect to the IMAP server.
The user's mailbox has already been migrated.
An Outlook Live mailbox wasn't found for the user.
Outlook Live couldn't sign in to the user account on the IMAP messaging system.
Android Send SMS and Make a phone call in Android Application
Android Preferences - Using Preferences in Android Tutorial

More Tutorials in Android
Getting Started with Android
Solution to error: unable to open connection to server due to security error
Android Preferences - Using Preferences in Android Tutorial
Android Send SMS and Make a phone call in Android Application
Android Emulator
Intent in Android to call one activity from another activity.
Animation sample program in Android
Another Animation sample program in Android
ArrayAdapter sample program in Android
Spinner sample program in Android
GridView sample program in Android
Gallery sample program in Android
Date and Time sample program in Android
Progress bar and downloading a file sample program in Android
Reading a file sample program in Android

More Latest News
Most Viewed Articles (in Android )
Progress bar and downloading a file sample program in Android
Date and Time sample program in Android
ArrayAdapter sample program in Android
Reading a file sample program in Android
AlertDialog sample program in Android
Animation sample program in Android
Another Animation sample program in Android
GridView sample program in Android
Spinner sample program in Android
Gallery sample program in Android
Reading and Writing a file to SD card sample program in Android
Intent in Android to call one activity from another activity.
Android Send SMS and Make a phone call in Android Application
Solution to error: unable to open connection to server due to security error
Error generating R.java from manifest
Most Emailed Articles (in Android)
GridView sample program in Android
Android Emulator
Reading a file sample program in Android
Reading and Writing a file to SD card sample program in Android
Solution to error: unable to open connection to server due to security error
Getting Started with Android
Animation sample program in Android
ArrayAdapter sample program in Android
Android Preferences - Using Preferences in Android Tutorial
Android Send SMS and Make a phone call in Android Application
AlertDialog sample program in Android
Spinner sample program in Android
Intent in Android to call one activity from another activity.
Error generating R.java from manifest
Another Animation sample program in Android