无法在 Android 上写入外部存储 [英] Can't write to external storage on Android
问题描述
我看到很多其他人在问同样的问题,但发布的解决方案都没有帮助我.
I see a bunch of other people asking this same question, but none of the solutions posted helped me.
我正在尝试将一个(二进制)文件从我的 Android 应用程序写入外部存储.我将 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
放入我的清单中,但我仍然无法创建任何文件.我用来创建文件的代码是
I'm trying to write a (binary) file to external storage from my Android app.
I put <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
into my manifest, but I still can't manage to create any files. The code I'm using to create files is
File folder = new File(Environment.getExternalStorageDirectory(), SAVE_DIRECTORY);
File toWrite = new File(folder, "save.bin");
if(!toWrite.exists()){
try {
if(!folder.mkdirs())
Log.e("Save", "Failed to create directories for save file!");
toWrite.createNewFile();
} catch (IOException e) {
Log.e("Save", "Failed to create save file! " + e.getMessage());
}
}
调用 mkdirs()
失败,createNewFile()
抛出 IOException
(ENOENT,因为目录不存在)
The call to mkdirs()
fails, and the createNewFile()
throws the IOException
(ENOENT, because the directory doesn't exist)
有人知道怎么回事吗?我什至尝试重新启动我的设备.我在 Nexus 7 上的 API 级别为 8(如果有什么不同的话).
Anybody know what's up? I've even tried rebooting my device. I'm on API level 8 on a Nexus 7, if it makes any difference.
推荐答案
首先你应该检查 ExternalStorageState
public static boolean isSDCARDAvailable(){
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
如果这个方法isSDCARDAvailable
返回true
,那么使用你的代码
if this method isSDCARDAvailable
return true
, then use your code
添加权限:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
这篇关于无法在 Android 上写入外部存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!