在安卓系统中将数据存储在SD卡上

7

使用数据存储页面的文档,我尝试将一些数据存储到SD卡中。 这是我的代码:

    // Path to write files to
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                  "/Android/data/"+ctxt.getString(R.string.package_name)+"/files/";
    String fname = "mytest.txt";

    // Current state of the external media
    String extState = Environment.getExternalStorageState();

    // External media can be written onto
    if (extState.equals(Environment.MEDIA_MOUNTED))
    {
        try {
            // Make sure the path exists
            boolean exists = (new File(path)).exists();  
            if (!exists){ new File(path).mkdirs(); }  

            // Open output stream
            FileOutputStream fOut = new FileOutputStream(path + fname);

            fOut.write("Test".getBytes());

            // Close output stream
            fOut.flush();
            fOut.close();

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

当我创建新的FileOutputStream时,我遇到了FileNotFound异常。我还注意到“mkdirs()”似乎没有创建目录。有人能告诉我我做错了什么吗?我正在AVD上进行测试,它带有一个2GB的sd卡和“hw.sdCard: yes”,Eclipse中的DDMS文件浏览器告诉我sd卡上唯一的目录是“LOST.DIR”。
2个回答

7

简单的事情会带来巨大的改变...谢谢!=) - BBoom

2
在读写SD卡之前,不要忘记检查SD卡是否已经挂载。
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接