How do you write to a folder on an SD card in Android?

后端 未结 4 1399
深忆病人
深忆病人 2020-11-22 07:50

I am using the following code to download a file from my server then write it to the root directory of the SD card, it all works fine:

package com.downloader;         


        
4条回答
  •  天涯浪人
    2020-11-22 08:43

    Add Permission to Android Manifest

    Add this WRITE_EXTERNAL_STORAGE permission to your applications manifest.

    
    
        
            
        
        
        
     
    

    Check availability of external storage

    You should always check for availability first. A snippet from the official android documentation on external storage.

    boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;
    String state = Environment.getExternalStorageState();
    
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        // Something else is wrong. It may be one of many other states, but all we need
        //  to know is we can neither read nor write
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }
    

    Use a Filewriter

    At last but not least forget about the FileOutputStream and use a FileWriter instead. More information on that class form the FileWriter javadoc. You'll might want to add some more error handling here to inform the user.

    // get external storage file reference
    FileWriter writer = new FileWriter(getExternalStorageDirectory()); 
    // Writes the content to the file
    writer.write("This\n is\n an\n example\n"); 
    writer.flush();
    writer.close();
    

提交回复
热议问题