将文件写入SD卡无法正常工作

时间:2011-06-17 22:09:51

标签: java android file sd-card

我写这篇文章是为了在SD卡中存储一个文件,但它没有用。

public class TestarFilesActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        File root = Environment.getExternalStorageDirectory();

        try {
            if (root.canWrite()) {
                File file = new File(root, "agora.txt");
                FileWriter fwriter = new FileWriter(file);
                BufferedWriter out = new BufferedWriter(fwriter);
                out.write("Hello world");
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }TestarFilesActivity.this.finish();
    }
}

这个问题是如何引起的?如何解决?我认为这一切都是正确的,我也在清单中写了许可。

3 个答案:

答案 0 :(得分:2)

检查此报告的问题,如果sd卡可写,似乎是相似的 - 检查Writing Text File to SD Card fails

答案 1 :(得分:2)

如果你在android模拟器中运行这个应用程序,你必须通过DevTools终端仿真器准备sdcard并使用linux命令检查sdcard目录为$ ls并允许sdcard 如果没有准备,请尝试以下

File file = new File(root, "/sdcard/agora.txt");
FileWriter fwriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fwriter);
out.write("Hello world");
out.close();

//Use this in manifest.xml  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

答案 2 :(得分:0)

您是否在AndroidManifest.xml中获得了sdcard的写入权限?

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