Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read and write files to removable sd card

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();
like image 284
AmmY Avatar asked Dec 13 '25 08:12

AmmY


2 Answers

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);
}
like image 109
Raghunandan Avatar answered Dec 15 '25 06:12

Raghunandan


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");
like image 41
Anshu Patel Avatar answered Dec 15 '25 07:12

Anshu Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!