Java 允许写入 SD 卡
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2121833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Permission to write to the SD card
提问by bugzy
I would like my app to archive the application DB to the SD card. In my code I check if the directory canWrite()
exists, and if not, throw an IOException
. In this particular instance, I am trying to copy the db file to the root directory on the SD card, but it's throwing an IOException
. How can I change the permission on a folder/file to be able to write to it?
我希望我的应用程序将应用程序数据库存档到 SD 卡。在我的代码中,我检查目录是否canWrite()
存在,如果不存在,则抛出一个IOException
. 在这个特定的例子中,我试图将 db 文件复制到 SD 卡上的根目录,但它抛出了一个IOException
. 如何更改文件夹/文件的权限以使其能够写入?
回答by Dave Webb
You're right that the SD Card directory is /sdcard
but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory()
to get the directory:
SD 卡目录是对的,/sdcard
但您不应该对其进行硬编码。相反,调用Environment.getExternalStorageDirectory()
以获取目录:
File sdDir = Environment.getExternalStorageDirectory();
If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
如果您还没有这样做,您需要通过将以下行添加到您的清单中来授予您的应用正确的写入 SD 卡的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
回答by samis
The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.
上面 Dave 的回答中建议的技术当然是一个很好的设计实践,是的,最终必须在 AndroidManifest.xml 文件中设置所需的权限才能访问外部存储。
However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).
但是,添加大多数(如果不是全部,不确定)“清单选项”的 Mono-esque 方法是通过实现活动(或服务)的类的属性。
The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).
Visual Studio Mono 插件会自动生成清单,因此最好不要手动篡改它(我确信在某些情况下没有其他选择)。
For example:
例如:
[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
protected override void OnCreate(Bundle bindle)
{
base.OnCreate(bindle);
}
}