Programming Tutorials

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

By: Ashley in Android Tutorials on 2011-07-03  

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>








Add Comment

* Required information
1000

Comments (2)

Avatar
New
Takersays...

It asks for permission .How to set permission.

Avatar
Admin
Garretsays...

In order to read and write to the SD card, you need to request the required permission in your app's AndroidManifest.xml file. You should add the following permissions to your manifest:

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

Also, starting from Android 10, you need to request the MANAGE_EXTERNAL_STORAGE permission to access files outside your app's private storage. To do that, you can add the following attribute to the <application> element in your manifest:

android:requestLegacyExternalStorage="true"

Most Viewed Articles (in Android )

compileSdkVersion vs buildToolsVersion in app/build.gradle

Android Send SMS and Make a phone call in Android Application

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

Intent in Android to call one activity from another activity.

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

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

GridView sample program in Android

Gallery sample program in Android

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Reading a file sample program in Android

Spinner sample program in Android

ArrayAdapter sample program in Android

Android Emulator

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Another Animation sample program in Android

Latest Articles (in Android)

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error

Related Tutorials

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error