参见StackOverflow

想必看到这篇文章的码友们估计都被Android获取选择的文件的路径坑过。具体是怎么被坑的呢:有的文件管理器返回的是content://协议,还有的返回的是file://协议。

废话不多说上代码。

一. 请求选择文件

private static final int FILE_SELECT_CODE = 0;private void showFileChooser() {   Intent intent = new Intent(Intent.ACTION_GET_CONTENT);   intent.setType("*/*");   intent.addCategory(Intent.CATEGORY_OPENABLE);   try {       startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);   } catch (android.content.ActivityNotFoundException ex) {     // Potentially direct the user to the Market with a Dialog     Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();   }}

二. 处理选择文件的回调

private static final String TAG = "ChooseFile";@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {   switch (requestCode) {       case FILE_SELECT_CODE:           if (resultCode == RESULT_OK) {               // Get the Uri of the selected file              Uri uri = data.getData();             Log.d(TAG, "File Uri: " + uri.toString());             // Get the path             String path = FileUtils.getPath(this, uri);            Log.d(TAG, "File Path: " + path);             // Get the file instance             // File file = new File(path);             // Initiate the upload       }     break;   }   super.onActivityResult(requestCode, resultCode, data);}

三. 对于第二步中的FileUtils.getPath代码如下

public static String getPath(Context context, Uri uri) throws URISyntaxException {   if ("content".equalsIgnoreCase(uri.getScheme())) {   String[] projection = { "_data" };    Cursor cursor = null;    try {     cursor = context.getContentResolver().query(uri, projection, null, null, null);     int column_index = cursor.getColumnIndexOrThrow("_data");     if (cursor.moveToFirst()) {         return cursor.getString(column_index);       }    } catch (Exception e) {       // Eat it  Or Log it.    }   } else if ("file".equalsIgnoreCase(uri.getScheme())) {     return uri.getPath();   }   return null;}

这段代码就是从Uri中获取文件路径的。

主要做了两个判断操作:

  1. 判断协议是不是content://开头,有的话就用ContentResolver去query查询文件真实位置。
  2. 判断协议是不是file://开头,如果是,那么uri.getPath()就是文件的真实路径。
    大家可以新建个FileUtils类,然后把上面的getPath()方法拷贝进去。

关注我的公众号.jpg

更多相关文章

  1. Android(安卓)NDK之JNI陷阱
  2. android_1
  3. Android(安卓)logback代码配置详解
  4. /mnt/sdcard与Environment.getExternalStorageDirectory()的使用
  5. AndroidManifest.xml文件综合详解
  6. FFmpeg编程开发笔记 —— Android(安卓)FFmpeg + SDL2.0简易播放
  7. android studio如何生成library project(库工程)
  8. java读取文本文件内容2
  9. 强制开启android webview debug模式使用Chrome inspect

随机推荐

  1. fastadmin cas登录404错误
  2. TP数据集处理\请求响应\模型(二)
  3. 超详细:如何在windous系统下使用wsl虚拟机
  4. 数据安全治理
  5. 交友盲盒源码|php盲盒源码开源程序搭建
  6. 四步教你做好问答类H5
  7. composer常用操作
  8. nvm管理node是真的香
  9. 仿淘宝移动端首页
  10. JS原生输入框变化监听事件