2 myc 100 myc_100 于 2012.10.10 15:05 提问

创建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);
    }
}

3个回答

yongyong_21
yongyong_21   2012.10.11 09:40
已采纳
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();
}
csh_34
csh_34   2012.10.10 16:27

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
clcurie_11
clcurie_11   2012.10.10 17:37

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

 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);
        }
    }
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!