尝试保存文件时没有这样的文件或目录

时间:2013-07-05 18:09:11

标签: android file directory save

对于我正在开发的应用程序,我想在SD卡上的文本文件中写入一些文本。我试过用下面的代码做到这一点。这给出了错误,但我不明白为什么。据我所知,我已完全按照网络上的所有示例。在logcat中,我看到第一个日志,但不是第二个日志,因此问题在于创建文件。你们知道出了什么问题吗?

public void saveDataToFile(String data, String fileName) {

    Log.d("Checks", "Trying to save data");

    try {
        // Set up the file directory
        String filePath = Environment.getExternalStorageDirectory().toString() + "/Data Folder";
        File fileDirectory = new File(filePath);
        fileDirectory.mkdirs();
        Log.d("Checks", "Directory created");

        // Set up the file itself
        File textFile = new File(fileDirectory, fileName);
        textFile.createNewFile();
        Log.d("Checks", "File created");

        // Write to the file
        FileOutputStream fileOutputStream = new FileOutputStream(textFile);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        outputStreamWriter.append(data);
        outputStreamWriter.close();
        fileOutputStream.close();

        Toast.makeText(mContext, "Done writing to SD card", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
    }

}

修改

原来我忘了为清单添加正确的权限。它现在有效!

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

1 个答案:

答案 0 :(得分:2)

您是否声明了正确使用权限来访问和写入外部SD卡?

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