在android中读取文件 - 文件权限被拒绝
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20063957/
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
Read file in android - file permission denied
提问by abdfahim
I want to read file from external storage. I uploaded the file in Eclipse DDMS to storage/sdcard (image below). But whenever I tried to read, I got an error of permission denied. Is there any problem in my file permission? Or I need to add anything in manifest file (I am not writing anything at the moment)?
我想从外部存储读取文件。我将 Eclipse DDMS 中的文件上传到 storage/sdcard(下图)。但是每当我尝试阅读时,我都会收到拒绝许可的错误。我的文件权限有问题吗?或者我需要在清单文件中添加任何内容(我目前没有写任何内容)?
Any help will be appreciated.
任何帮助将不胜感激。
Code:
代码:
public void extimport(View v){
EditText xedittxt = (EditText) findViewById(R.id.frmexttxt);
String xedit = xedittxt.getText().toString();
xedit = xedit.trim();
File file;
file = new File(xedit);
StringBuilder text = new StringBuilder();
Log.d("fcheck",""+xedit);
try {
BufferedReader br = new BufferedReader(new FileReader(file)); //THIS LINE THROWS ERROR
Log.d("fcheck","f3"); //This line never got printed
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
resultView = (TextView) findViewById(R.id.header);
resultView.setText(text);
}
catch (IOException e) {
Log.d("File open error",""+e);
Toast.makeText(getApplicationContext(), "Error opening the file.", Toast.LENGTH_SHORT).show();
}
}
LogCat:
日志猫:
11-19 00:21:54.252: D/fcheck(5885): /storage/sdcard/mylibman.csv
11-19 00:21:54.272: D/File open error(5885): java.io.FileNotFoundException: /storage/sdcard/mylibman.csv: open failed: EACCES (Permission denied)
回答by GrIsHu
Make sure you have added the permission to read external storage in your manifest file.
确保您已在清单文件中添加读取外部存储的权限。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
回答by Vsw10
I was experiencing the same problem and it can be easily removed by following either of these steps: 1. Install your app by using -g if installing on Android N and O versions. 2. Grant permission manually Settings->apps->"app_name"->Permissions->Enable Switch
我遇到了同样的问题,可以通过以下任一步骤轻松删除它: 1. 如果在 Android N 和 O 版本上安装,请使用 -g 安装您的应用程序。2. 手动授予权限 Settings->apps->"app_name"->Permissions->Enable Switch
For Both steps 1 and 2, define uses-permission
对于第 1 步和第 2 步,定义使用权限
android:name="android.permission.WRITE_EXTERNAL_STORAGE" and uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" in AndroidManifest.xml
Like this :
像这样 :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="...">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- all permissions here -->
<application
...