store data text to SD Card in android?

2019-08-24 08:45发布

问题:

I have to store data text to SD Card.

This is my code :

 try {

                File myFile = new File(Environment.getExternalStorageDirectory()+"/mnt/sdcard/mysdfile.txt");

                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter = 
                                        new OutputStreamWriter(fOut);
                myOutWriter.append(txtData.getText());
                myOutWriter.close();
                fOut.close();
                Toast.makeText(getBaseContext(),
                        "Done writing SD 'mysdfile.txt'",
                        Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }

In AndroidMainfest i have :

<uses-permission android:name="android.permisson.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

I don't understand Why it don't work ?

In Toast reported error :Permission denied?

Please help me .

回答1:

You can also try this https://github.com/uberspot/AndroidStorageUtils it's a wrapper class/package that makes storage usage in android a bit easier. :) It has a "saveStringOnExternalStorage" method as well.



回答2:

Try this code must solve issues...

try{
    String filename = "filename.txt";
    File myFile = new File(Environment.getExternalStorageDirectory(), filename);

    if(!myFile.exists()) 
        myFile.createNewFile();
    FileOutputStream fos;
    byte[] data = txtData.getBytes();
    try {
        fos = new FileOutputStream(myFile);
        fos.write(data);
        fos.flush();
        fos.close();
    } 
    catch (FileNotFoundException e) {
    // handle exception
  } catch (IOException e) {
    // handle exception
  }