使用data-storage page in the docs,我试图将一些数据存储到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卡的AVD和“hw.sdCard:yes”,Eclipse中的DDMS文件浏览器告诉我,SD卡上唯一的目录是“LOST.DIR”。
答案 0 :(得分:7)
您是否已经提供了application permission to write to the SD Card?
您可以通过adding the following to your AndroidManifest.xml
执行此操作:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 1 :(得分:2)
在读取或写入SD卡之前,不要忘记检查SD卡是否安装?
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)