Android-Save file to Removable SD and Read

984 views Asked by At

I am trying to make an Android Activity to write a test file to the removable SD card of the device. I then need to be able to verify it was written. I have been able to write to the internal storage of the phone (called external storage, although it is not), but not the removable SD card. I guess I need to get the path correct.

I have been able to check the existence of the removable SD card with this code, but have not been able to translate it to writing the file:

    String secStore = System.getenv("SECONDARY_STORAGE");
    File path = new File(secStore);
    StatFs stat = new StatFs(path.getPath());

Here is my code for writing the test file bt as I said-it writes to the internal storage of the device:

File dir = new File(android.os.Environment.getExternalStorageDirectory(), "TestFolder");
        if (!dir.exists()) {
            dir.mkdirs();
        }
         String filename = "SD_Test.txt";
            try {
                File f = new File(dir + File.separator + filename);
                FileOutputStream fOut = new FileOutputStream(f);
                OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                myOutWriter.append("Testing SD Card");
                myOutWriter.flush();
                myOutWriter.close();
                fOut.close();
                if(f.exists()){
                    Toast.makeText(getBaseContext(),
                            "File Created",
                            Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

    }

Please Help, I have been working on this for days and am stuck!!

1

There are 1 answers

0
CommonsWare On

Here is my code for writing the test file bt as I said-it writes to the internal storage of the device:

It writes to what the Android SDK refers to as external storage.

I have been able to check the existence of the removable SD card with this code

There is no requirement for that environment variable to exist, let alone for it to have some meaning.

but have not been able to translate it to writing the file

You do not have access to arbitrary filesystem locations on removable storage on Android 4.4+. Use getExternalFilesDirs(), getExternalCacheDirs(), or getExternalMediaDirs(). If these methods return 2+ entries, the second and subsequent ones are locations on removable storage where you can read and write.