创建Android外部存储器文件问题

我想创建一个.txt文件并将其存储在Android手机的外部存储器。我增加了Android Manifest权限。我运行代码时不给出任何错误提示,但文件却创建不了。我不知道代码哪里出错,请高人指点,谢谢。

public void createExternalStoragePrivateFile(String data) {
    // Create a path where we will place our private file on external
    // storage.
    File file = new File(myContext.getExternalFilesDir(null), "state.txt");

    try {

        FileOutputStream os = null; 
        OutputStreamWriter out = null;
        os = myContext.openFileOutput(data, Context.MODE_PRIVATE);
        out = new OutputStreamWriter(os);
        out.write(data);
        os.close();

        if(hasExternalStoragePrivateFile()) {
            Log.w("ExternalStorageFileCreation", "File Created");
        } else {
            Log.w("ExternalStorageFileCreation", "File Not Created");
        }

    } catch (IOException e) {
        // Unable to create file, likely because external storage is
        // not currently mounted.
        Log.w("ExternalStorage", "Error writing " + file, e);
    }
}
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {

     FileOutputStream os = new FileOutputStream(file, true); 
     OutputStreamWriter out = new OutputStreamWriter(os);
         out.write(data);
     out.close();
}

你需要添加一个正确的权限:

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

我之前也遇见过这个问题,用这段代码能实现:

 public void createExternalStoragePrivateFile(String data) {
        // Create a path where we will place our private file on external
        // storage.
        File file = new File(myContext.getExternalFilesDir(null), "state.txt");


        try {

            FileOutputStream os = new FileOutputStream(file); 
            OutputStreamWriter out = new OutputStreamWriter(os);

            out.write(data);
            out.close();

            if(hasExternalStoragePrivateFile()) {
                Log.w("ExternalStorageFileCreation", "File Created");
            } else {
                Log.w("ExternalStorageFileCreation", "File Not Created");
            }

        } catch (IOException e) {
            // Unable to create file, likely because external storage is
            // not currently mounted.
            Log.w("ExternalStorage", "Error writing " + file, e);
        }
    }