[英]Android correct way to get File from 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 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 {...}
似乎文件沒有成功創建。 我的日志結果是:
方法 file.exist() 返回我該文件不存在。 為什么?
在其他代碼中,我嘗試為許多其他操作管理文件:
...
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:","");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.