Android从Uri获取文件的正确方法
我使用以下方法从本地存档中选择PDF:Android从Uri获取文件的正确方法,android,file,pdf,path,uri,Android,File,Pdf,Path,Uri,我使用以下方法从本地存档中选择PDF: startActivityForResult(Intent.createChooser(new Intent().setType("application/pdf").setAction(Intent.ACTION_GET_CONTENT), getString(R.string.str_select_file)), request_id_archive); 管理结果: @Override protected void onActivit
startActivityForResult(Intent.createChooser(new Intent().setType("application/pdf").setAction(Intent.ACTION_GET_CONTENT), getString(R.string.str_select_file)), request_id_archive);
管理结果:
@Override
protected void onActivityResult(int request_code, int result_code, Intent data) {
super.onActivityResult(request_code, result_code, data);
if (request_code == request_id_archive && result_code == RESULT_OK && data != null && data.getData() != null) {
Uri myuri = data.getData();
String mypath = myuri.getPath();
File myfile = new File(mypath);
Log.d("mylog1", uri.toString());
Log.d("mylog2", uri.getPath());
Log.d("mylog3", f.getPath());
Log.d("mylog4", f.toString());
Log.d("mylog5", Boolean.toString(f.exists()));
}
else {...}
文件似乎没有成功创建。
我的日志的结果是:
- mylog1->content://media/external/file/7406
- mylog2->/external/file/7406
- mylog3->/external/file/7406
- mylog4->/external/file/7406
- mylog5->false
...
InputStream inputStream = new FileInputStream(file);
...
但我的应用程序在Logcat中崩溃,我看到:
java.io.FileNotFoundException: /document/raw:/storage/emulated/0/Download/20180702_121938.pdf (No such file or directory)
我正在Android 7上测试我的代码。您需要将'document/raw'替换为空字符串,因此您需要在访问文件之前添加此代码:
if(mypath.contains("document/raw:")){
mypath = mypath.replace("/document/raw:","");
}
试试这个`Intent intentPDF=newintent(Intent.ACTION\u GET\u CONTENT);intentPDF.setType(“application/pdf”);intentPDF.addCategory(Intent.CATEGORY_可打开)`getPath()不提供文件系统路径。此外,没有正确的方法从这样的uri获取文件。您尝试这样做的方式完全错误。
document/raw:/storage/simulated/0/Download/20180702_121938.pdf
这不是有效路径。尝试/storage/emulated/0/Download/20180702_121938.pdf
@greenapps使用您的建议我解决了使用子字符串uri.getPath()删除“document/raw:”的问题。替换(“document/raw:,”。它起作用了。无论如何,这只是一个解决办法。正如您所说的“您尝试这样做的方式完全是错误的。”那么,从onActivityResult获取文件的正确方式是什么呢?对不起,但我确实理解您为什么说“您不需要文件”。onActivityResult只返回一个Uri。我需要一个文件对象来执行我的操作…经过3个小时的调试和搜索,您保存了我。