3

How to read and write files to removable sd card in Android?

I want to store Android Id in Text file. The text file should be created on external sdcard.

Code:

PackageManager m = getPackageManager();
String s = getPackageName();
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
File myFile = new File(s + "/MyDoople.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(TxtS.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Text Updated",Toast.LENGTH_SHORT).show();

The Second is

 File sdCard = new File("file:///mnt/external_sd/");
 File myFile = new File(sdCard, "test.txt");
 FileWriter writer = new FileWriter(myFile); 
 writer.append(TESTSTRING);
 writer.flush(); 
 writer.close();
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
AmmY
  • 1,821
  • 1
  • 20
  • 31
  • What did you try.. show us... – amalBit Jun 08 '13 at 07:54
  • I edit my question pls see again. – AmmY Jun 08 '13 at 08:03
  • This is bad - `file:///mnt/external_sd/` and how do you know it exists? `Environment.getExternalStorageDirectory()` – Simon Jun 08 '13 at 08:11
  • possible duplicate of [Android write to sd card folder](http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder) – Simon Jun 08 '13 at 08:13
  • @Simon- Environment.getExternalStorageDirectory() show the external memory(inbulid) of the Device. but I want to use Removable i.e Secondary memory of the device. and I already tried which you link is shown. – AmmY Jun 08 '13 at 08:19
  • `Environment.getExternalStorageDirectory() show the external memory(inbulid) of the Device` No it does not. Please read the documentation. – Simon Jun 08 '13 at 08:23
  • http://stackoverflow.com/questions/5694933/find-an-external-sd-card-location – Simon Jun 08 '13 at 08:30
  • @Aman what you mean by "external memory(inbuild)"?. – Raghunandan Jun 08 '13 at 08:51
  • @Raghunandan external memory is which is provided by the Device company. and I want to write file in external memory-card which is removable. – AmmY Jun 08 '13 at 09:01
  • @Aman yes the below works fine on my device. I don't understand your comment. You have built in phone memory and external sd card. Now you can use the code in my answer to write to sdcard. I don't understand "external memory provided by manufacturer"? – Raghunandan Jun 08 '13 at 09:03
  • @Aman check the edit might help you. On what device do you test? – Raghunandan Jun 08 '13 at 09:10
  • @Raghunandan: yes your code is working well. but it is not my solution. It store th file in phone's memory. I want to store the file in Micro SD card. – AmmY Jun 08 '13 at 09:16
  • I m using Micro-max Funbook – AmmY Jun 08 '13 at 09:31

5 Answers5

6

Try the below. Use Environment.getExternalStorageDirectory() to get the path

  File dir =new File(android.os.Environment.getExternalStorageDirectory(),"MyFolder");
    if(!dir.exists())
    {
           dir.mkdirs();
    }    
    String filename= "MyDoople.txt";
    try
    {
    File f = new File(dir+File.separator+filename);

    FileOutputStream fOut = new FileOutputStream(f);
    OutputStreamWriter myOutWriter = new OutputStreamWriter(
            fOut);
    myOutWriter.append("Mytest");
    myOutWriter.close();
    fOut.close();
    Toast.makeText(getBaseContext(),
            "Text Updated",
            Toast.LENGTH_SHORT).show();
   }
    catch(Exception e)
    {
        e.printStackTrace();
    }

To update:

try
{

FileWriter fileWritter = new FileWriter(f,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write("Mydata");
bufferWritter.close();
}
 catch(Exception e)
 {
e.printStackTrace();
 }

Result on my device when i opened with a text file viewer.

enter image description here

Edit:

The below is hackish and not the recommended way.

In my device (Samsung Galaxy s3) my internal phone memory is named sdCard0 and my external extSdcard. This Environment.getExternalStorageDirectory() will give path of internl memory. In such cases you can use the below to get path of external memory.

String externalpath = new String();
String internalpath = new String();

public  void getExternalMounts() {
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.exec("mount");
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
String line;

BufferedReader br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
    if (line.contains("secure")) continue;
    if (line.contains("asec")) continue;

    if (line.contains("fat")) {//external card
        String columns[] = line.split(" ");
        if (columns != null && columns.length > 1) {
            externalpath = externalpath.concat("*" + columns[1] + "\n");
        }
} 
        else if (line.contains("fuse")) {//internal storage
        String columns[] = line.split(" ");
        if (columns != null && columns.length > 1) {
            internalpath = internalpath.concat(columns[1] + "\n");
        }
    }
}
}
catch(Exception e)
{
    e.printStackTrace();
}
  System.out.println("Path  of sd card external............"+externalpath);
  System.out.println("Path  of internal memory............"+internalpath);
}
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • I get the path already but when my code write or read the file then the error is occurred. The error is: java.io.FileNotFoundException: open failed: ENOENT (No such file or directory) Sorry for my english.... – AmmY Jun 08 '13 at 09:29
  • @Aman check if you have created a directory. If you do it right it should work. the above works on my device and i have posted the snapshot – Raghunandan Jun 08 '13 at 09:42
  • @Aman i came across a user who had the same problem with funbook. I suggest you try it on a different device and then post the result here – Raghunandan Jun 08 '13 at 09:45
  • @Raghunandan- I copy paste your code and its work. but it create a file in phone memory. I don't want to create a file in phone memory. I want to create or write file in External memory Card. – AmmY Jun 08 '13 at 09:47
  • @Aman did you try the edit. use the external path by using the code in edit. Also test it on a different device to check if the behaviour repeats – Raghunandan Jun 08 '13 at 09:56
  • @Raghunandan- No its not working in another device. Plz check this image to see the result... https://www.dropbox.com/s/x2hqyxti6isn0q3/Screenshot_2013-06-08-15-27-02.png – AmmY Jun 08 '13 at 10:18
  • @Raghunandan- yes I use the code of edit to get the path and your answer to write the file. – AmmY Jun 08 '13 at 10:23
  • @Aman i can't think of any other reason why it won't work. it works on my device – Raghunandan Jun 08 '13 at 10:25
  • again this error occurred - /MyFolder/MyDoople.txt: open failed: ENOENT (No such file or directory) – AmmY Jun 08 '13 at 10:30
  • @Aman try this http://stackoverflow.com/questions/15820148/cannot-write-to-sd-card-on-android-phone/15820695#15820695 – Raghunandan Jun 08 '13 at 10:45
  • @Raghunandan- No Its not working Sir, I think its is manufecture's Default. http://code.google.com/p/android/issues/detail?id=18559 http://help.quickoffice.com/detail?topic=4841511 – AmmY Jun 08 '13 at 11:40
  • @Raghunandan- I tested you code and the externalpath retuens */mnt/extsd */mnt/sdcard I think the code is not working correctly i am unable to post answer. so I did not show you the code. – AmmY Jun 10 '13 at 05:03
  • @Aman i din't understand your comment. this is /mnt/extsd path of external sdcard. In samsung salaxy s3 this is /mnt/sdcard path of internal phone memory. So what is not working in your case? – Raghunandan Jun 10 '13 at 05:05
  • I show both externalpath and internalpath string in diffrent toast. the externalpath's Toast shows */mnt/extsd */mnt/sdcard both and internalpath's Toast Shows blank. – AmmY Jun 10 '13 at 05:53
  • @raghunandan- Check this link. set externalpath string to TextView tv. and the result is in the image. https://www.dropbox.com/s/jbdnec82cj7ro61/fullimage.jpg – AmmY Jun 10 '13 at 11:25
  • @Aman that looks alright to me coz i do get the same on my s3 – Raghunandan Jun 10 '13 at 11:26
  • @Raghunandan- May you send you project sample so I can check it on my tab. – AmmY Jun 10 '13 at 11:51
3
private static String getExternalStoragePath(Context mContext) {

    StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
    Class<?> storageVolumeClazz = null;
    try {
        storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
        Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
        Method getPath = storageVolumeClazz.getMethod("getPath");
        Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
        Object result = getVolumeList.invoke(mStorageManager);
        final int length = Array.getLength(result);
        for (int i = 0; i < length; i++) {
            Object storageVolumeElement = Array.get(result, i);
            String path = (String) getPath.invoke(storageVolumeElement);
            boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
            if (removable == true) {
                return path;
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

and enter this code.

It return path of SD Card path if SD card is available

and then you can use that path .

String sdCardPath = getExternalStoragePath(context);
File Path1 = new File(sdCardPath + "NewFolder");
    if (!Path1.exists()) {
        Path1.mkdir();
    }
File file = new File(Path1, "test.txt");
S.Smit
  • 3
  • 6
0

Maybe you forget these permissions.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Dev2007
  • 29
  • 3
  • 1
    I already use this permission in Manifest file. It use to store only external memory of device not Removable memory. – AmmY Jun 08 '13 at 08:05
0
      package com.example.writeinsdcard;

       import android.os.Bundle;
       import android.app.Activity;
       import android.view.Menu;
       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.os.Environment;
       import android.util.Log;
       import android.widget.TextView;

       public class MainActivity extends Activity {

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

             @Override
             protected void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.fragment_main);

                      tv = (TextView) findViewById(R.id.TextView01);
                      checkExternalMedia();
                      writeToSDFile();
                      readRaw();

             }

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

             /** 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);


                      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("Howdy do to you.");
                               pw.println("Here is a second line.");
                               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:\n"+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("\n\nData read from res/raw/textfile.txt:\n");
                      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");
             }
       }

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

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <!--permission to write external storage  -->
    <uses-permission 
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.writesdcard.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>
vikseln
  • 458
  • 6
  • 8
-4

My question is solved. I directly use the path "/mnt/external_sd/.. Path of File.".

But it was only work with my Device

AmmY
  • 1,821
  • 1
  • 20
  • 31