Android explains the operation example of sdcard extended card

  • 2020-06-01 10:58:41
  • OfStack

The Android operation on the sdcard extension carver is just a normal file operation, but there are still some things to be aware of. Such as:

1. Add sdcard operation permission;

2. Confirm the existence of sdcard;

3. You cannot directly create a file in the root directory other than sdcard, but you need to create a directory first and then create a file;

Examples are as follows:

(1) add sdcard operation permission in AndroidManifest.xml


<!-- sdcard permissions  -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

(2) variable declaration:


private final static String PATH = "/sdcard/digu";
private final static String FILENAME = "/notes.txt";

(3) write to sdcard:


/**
*  Write files 
*/
private void onWrite() {
   try {
     Log.d(LOG_TAG, "Start Write");
     //1. To determine if there is sdcard
     if (Environment.MEDIA_MOUNTED.equals(Environment
         .getExternalStorageState())) {
       // directory 
       File path = new File(PATH);
       // file 
       File f = new File(PATH + FILENAME);
       if(!path.exists()){
         //2. Create a directory that can be created at application startup 
         path.mkdirs();
       }
       if (!f.exists()) {
         //3. Create a file 
         f.createNewFile();
       }
       OutputStreamWriter osw = new OutputStreamWriter(
           new FileOutputStream(f));
       //4. Write files from EditView Get the text value 
       osw.write(editor.getText().toString());
       osw.close();
     }
   } catch (Exception e) {
     Log.d(LOG_TAG, "file create error");
   }
 }


Related articles: