Blog : Write a file in external storage in Android

Write a file in external storage in Android


I want to create a file in external storage sdCard and write to it.I have searched through internet and try but not getting the result,I have added permission in Android Manifest file as well,I am doing this on Emulator,I am trying the following code and getting a ERRR", "Could not create file".

btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
  btnWriteSDFile.setOnClickListener(new OnClickListener() {
  //private Throwable e;

  @Override
  public void onClick(View v) {
  // write on SD card file data from 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();
  } catch (Exception e) {
  Log.e("ERRR", "Could not create file",e);
  }

  }// onClick
  }); // btnWriteSDFile

You can do this with this code also.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;

 public class WriteSDCard extends Activity {

 private static final String TAG = "MEDIA";
 private TextView tv;

  /** Called when the activity is first created. */
@Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);   
  tv = (TextView) findViewById(R.id.TextView01);
  checkExternalMedia();
  writeToSDFile();
  readRaw();
 }

/** Method to check whether external media available and writable. This is adapted from
  http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */

 private void checkExternalMedia(){
  boolean mExternalStorageAvailable = false;
  boolean mExternalStorageWriteable = false;
  String state = Environment.getExternalStorageState();

  if (Environment.MEDIA_MOUNTED.equals(state)) {
  // Can read and write the media
  mExternalStorageAvailable = mExternalStorageWriteable = true;
  } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
  // Can only read the media
  mExternalStorageAvailable = true;
  mExternalStorageWriteable = false;
  } else {
  // Can't read or write
  mExternalStorageAvailable = mExternalStorageWriteable = false;
  }   
  tv.append("\n\nExternal Media: readable="
  +mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}

/** Method to write ascii text characters to file on SD card. Note that you must add a
  WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
  a FileNotFound Exception because you won't have write permission. */

private void writeToSDFile(){

  // Find the root of the external storage.
  // See http://developer.android.com/guide/topics/data/data-  storage.html#filesExternal

  File root = android.os.Environment.getExternalStorageDirectory();
  tv.append("\nExternal file system root: "+root);

  // See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder

  File dir = new File (root.getAbsolutePath() + "/download");
  dir.mkdirs();
  File file = new File(dir, "myData.txt");

  try {
  FileOutputStream f = new FileOutputStream(file);
  PrintWriter pw = new PrintWriter(f);
  pw.println("Hi , How are you");
  pw.println("Hello");
  pw.flush();
  pw.close();
  f.close();
  } catch (FileNotFoundException e) {
  e.printStackTrace();
  Log.i(TAG, "******* File not found. Did you" +
  " add a WRITE_EXTERNAL_STORAGE permission to the  manifest?");
  } catch (IOException e) {
  e.printStackTrace();
  }   
  tv.append("\n\nFile written to "+file);
}

/** Method to read in a text file placed in the res/raw directory of the application. The
  method reads in all lines of the file sequentially. */

private void readRaw(){
  tv.append("\nData read from res/raw/textfile.txt:");
  InputStream is = this.getResources().openRawResource(R.raw.textfile);
  InputStreamReader isr = new InputStreamReader(is);
  BufferedReader br = new BufferedReader(isr, 8192);  // 2nd arg is buffer size

  // More efficient (less readable) implementation of above is the composite expression
  /*BufferedReader br = new BufferedReader(new InputStreamReader(
  this.getResources().openRawResource(R.raw.textfile)), 8192);*/

  try {
  String test;   
  while (true){   
  test = br.readLine();   
  // readLine() returns null if no more lines in the file
  if(test == null) break;
  tv.append("\n"+"  "+test);
  }
  isr.close();
  is.close();
  br.close();
  } catch (IOException e) {
  e.printStackTrace();
  }
  tv.append("\n\nThat is all");
}}


 
0
 
down vote  I know this is a bit late but i have don it this way, it creates a Documents directory and then a sub-directory for the application and saved the files to it.

  public class loadDataTooDisk extends AsyncTask
{
  String sdCardFileTxt;
  @Override
  protected String doInBackground(String... params)
  {

  //check to see if external storage is avalibel
  checkState();
  if(canW == canR == true)
  {
  //get the path to sdcard
  File pathToExternalStorage = Environment.getExternalStorageDirectory();
  //to this path add a new directory path and create new App dir (InstroList) in /documents Dir
  File appDirectory = new File(pathToExternalStorage.getAbsolutePath()  + "/documents/InstroList");
  // have the object build the directory structure, if needed.
  appDirectory.mkdirs();
  //test to see if it is a Text file
  if ( myNewFileName.endsWith(".txt") )
  {

  //Create a File for the output file data
  File saveFilePath = new File (appDirectory, myNewFileName);
  //Adds the textbox data to the file
  try{
  String newline = "\r\n";
  FileOutputStream fos = new FileOutputStream (saveFilePath);
  OutputStreamWriter OutDataWriter  = new OutputStreamWriter(fos);

  OutDataWriter.write(equipNo.getText() + newline);
  // OutDataWriter.append(equipNo.getText() + newline);
  OutDataWriter.append(equip_Type.getText() + newline);
  OutDataWriter.append(equip_Make.getText()+ newline);
  OutDataWriter.append(equipModel_No.getText()+ newline);
  OutDataWriter.append(equip_Password.getText()+ newline);
  OutDataWriter.append(equipWeb_Site.getText()+ newline);
  //OutDataWriter.append(equipNotes.getText());
  OutDataWriter.close();

  fos.flush();
  fos.close();

  }catch(Exception e){
  e.printStackTrace();
  }
  }
  }
  return null;
  }
}

This one creates the file name

  private String BuildNewFileName()
  { // creates a new filr name
  Time today = new Time(Time.getCurrentTimezone());
  today.setToNow();

  StringBuilder sb = new StringBuilder();

  sb.append(today.year + "");  // Year)
  sb.append("_");
  sb.append(today.monthDay + "");  // Day of the month (1-31)
  sb.append("_");
  sb.append(today.month + "");  // Month (0-11))
  sb.append("_");
  sb.append(today.format("%k:%M:%S"));  // Current time
  sb.append(".txt");  //Completed file name

  myNewFileName = sb.toString();
  //Replace (:) with (_)
  myNewFileName = myNewFileName.replaceAll(":", "_");

  return myNewFileName;
  }


ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext()); //getappcontext for just this activity context get
 File file = contextWrapper.getDir(file_path, Context.MODE_PRIVATE);  
 if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
 {
  saveToExternalStorage.setEnabled(false);
 }
 else
 {
  External_File = new File(getExternalFilesDir(file_path), file_name);//if ready then create a file for external
 }

}
 try
  {
  FileInputStream fis = new FileInputStream(External_File);
  DataInputStream in = new DataInputStream(fis);
  BufferedReader br =new BufferedReader(new InputStreamReader(in));
  String strLine;
  while ((strLine = br.readLine()) != null)
  {
  myData = myData + strLine;
  }
  in.close();
  }
  catch (IOException e)
  {
  e.printStackTrace();
  }
  InputText.setText("Save data of External file::::  "+myData);


private static boolean isExternalStorageReadOnly()
{
 String extStorageState = Environment.getExternalStorageState();
 if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState))
 {
  return true;
 }
 return false;
}

private static boolean isExternalStorageAvailable()
{
 String extStorageState = Environment.getExternalStorageState();
 if (Environment.MEDIA_MOUNTED.equals(extStorageState))
 {
  return true;
 }
 return false;
}