Android(安卓)选择文件并获取路径
16lz
2021-01-26
参见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中获取文件路径的。
主要做了两个判断操作:
- 判断协议是不是content://开头,有的话就用ContentResolver去query查询文件真实位置。
- 判断协议是不是file://开头,如果是,那么uri.getPath()就是文件的真实路径。
大家可以新建个FileUtils类,然后把上面的getPath()方法拷贝进去。
关注我的公众号.jpg
更多相关文章
- Android(安卓)NDK之JNI陷阱
- android_1
- Android(安卓)logback代码配置详解
- /mnt/sdcard与Environment.getExternalStorageDirectory()的使用
- AndroidManifest.xml文件综合详解
- FFmpeg编程开发笔记 —— Android(安卓)FFmpeg + SDL2.0简易播放
- android studio如何生成library project(库工程)
- java读取文本文件内容2
- 强制开启android webview debug模式使用Chrome inspect