Android Snippet – Write file to SD Card

Android Snippet – Write file to SD Card

In this simple android snippet code we are going to learn how to write to SD card in android. For a detail tutorials on android application development please refer to our blog section.

There are situations that require to write file in external storage. One of the best option is to use the SD card for the storage.

Before we start, the first thing I will do is to list the environment and tools I used in this android snippet tutorial but feel free to use whatever environment or tools you are familiar with.

Windows 7

Android Studio

Samsung Galaxy Fame Lite

Min SDK 8

Target SDK 19

To create a new android application project, following the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: WriteToSDCard

Package: com.inducesmile.writetosdcard

Keep other default selections.

Continue to click on next button until Finish button is active, then click on Finish Button

When you are done with creating your project, copy and paste the following code snippet to your project. Replace the code in your MainActivity.java file with the following code. Make sure you change the package name if you did not use the same package.

package writetosdcard.inducesmile.com.writetosdcard;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends ActionBarActivity {
String pathToFile = "fileNameToWriteToSD";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard, pathToFile);

try{
FileOutputStream os = new FileOutputStream(file);
String textContent = "This is the content of the file";
os.write(textContent.getBytes());
os.close();
}catch(FileNotFoundException ex){
System.out.println("Error: " + ex.getMessage() );
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}

public static boolean isExternalStorageWriteable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) return true;
return false;
}
}

It is important to note that the method that was add in the program as shown below is use to check if the external storage is writable before writing to it.

public static boolean isExternalStorageWriteable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) return true;
return false;
}

You should also remember to add this permission for this application to work.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="writetosdcard.inducesmile.com.writetosdcard" >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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>
</manifest>

Save the file and run your project. If everything works fine you will see that a file has been written to your SDCard.

You can download the code for this tutorial below. If you are having hard time downloading the tutorials, you can drop your email address and I will forward it to your inbox.

Remember to subscribe with your email so that you will be among the first to receive our new post once it is published

Add a Comment