在Android中从外部存储打开文件 [英] Open file from external storage in Android
问题描述
这可能是一种快速修复方法,但是目前我无法正常工作...
This could probably be a fast fix but currently I am unable to get this working...
我在解析XML文件时有一个asynctask.如果我将XML文件放在资产文件夹中,则可以打开并解析它.
I have an asynctask where I am parsing a XML file. If I place an XML file in the assets folder i can open and parse it no problem.
但是,如果我尝试从外部存储打开XML文件,则会失败.
But if I try to open a XML file from external storage it fails.
这是我的异步任务:
private class async extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
while (!isCancelled()) {
try {
NodeList nList;
Node node;
InputStream is = getAssets().open("file.xml");
// this works
File is = new File("/storage/emulated/0/test.xml");
// this fails
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
我收到此错误:
I/System.out: File path: /storage/emulated/0/test.xml
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/test.xml (Permission denied)
这些权限在我的清单中:
These permissions are in my manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
有人可以告诉我为什么我会收到此错误吗?
Could someone tell me why I am getting this error?
谢谢!
推荐答案
我看到了您的错误消息:
I see your error message :
java.io.FileNotFoundException:/storage/emulated/0/test.xml(权限被拒绝)
java.io.FileNotFoundException: /storage/emulated/0/test.xml (Permission denied)
请记住,您必须在运行Android 6.0的操作系统上运行必须实现 尝试读取或写入外部存储之前的运行时权限.
Remember that running on running Android 6.0 you must implement runtime permissions before you try to read or write the external storage.
将其设置为manifest.xml对于使用Android 6.0及更高版本的设备是不够的:
setting this into your manifest.xml is not enough for devices with Android 6.0+:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
这篇关于在Android中从外部存储打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!