2010-05-24 93 views
7

使用data-storage page in the docs,我尝试将一些数据存储到SD卡。 这是我的代码:在Android中将数据存储在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()”似乎没有创建目录。

谁能告诉我我做错了什么?

我在使用2GB sd卡和“hw.sdCard:yes”的AVD上进行测试,Eclipse中DDMS的文件浏览器告诉我,SD卡上唯一的目录是“LOST.DIR”。

回答

2

之前读取或写入SD卡,不要忘记检查SD卡安装或没有?

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)