android uri 解析獲取檔案真實路徑(相容7.0+)
阿新 • • 發佈:2018-12-13
主要是相容7.0以後的fileProvider 把URI 以content provider 方式 對外提供的解析方法
public static File getFileFromUri(Uri uri, Context context) { if (uri == null) { return null; } switch (uri.getScheme()) { case "content": return getFileFromContentUri(uri, context); case "file": return new File(uri.getPath()); default: return null; } }
/** * Gets the corresponding path to a file from the given content:// URI * * @param contentUri The content:// URI to find the file path from * @param context Context * @return the file path as a string */ private static File getFileFromContentUri(Uri contentUri, Context context) { if (contentUri == null) { return null; } File file = null; String filePath; String fileName; String[] filePathColumn = {MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME}; ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query(contentUri, filePathColumn, null, null, null); if (cursor != null) { cursor.moveToFirst(); filePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0])); fileName = cursor.getString(cursor.getColumnIndex(filePathColumn[1])); cursor.close(); if (!TextUtils.isEmpty(filePath)) { file = new File(filePath); } if (!file.exists() || file.length() <= 0 || TextUtils.isEmpty(filePath)) { filePath = getPathFromInputStreamUri(context, contentUri, fileName); } if (!TextUtils.isEmpty(filePath)) { file = new File(filePath); } } return file; }
/** * 用流拷貝檔案一份到自己APP目錄下 * * @param context * @param uri * @param fileName * @return */ public static String getPathFromInputStreamUri(Context context, Uri uri, String fileName) { InputStream inputStream = null; String filePath = null; if (uri.getAuthority() != null) { try { inputStream = context.getContentResolver().openInputStream(uri); File file = createTemporalFileFrom(context, inputStream, fileName); filePath = file.getPath(); } catch (Exception e) { L.e(e); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception e) { L.e(e); } } } return filePath; } private static File createTemporalFileFrom(Context context, InputStream inputStream, String fileName) throws IOException { File targetFile = null; if (inputStream != null) { int read; byte[] buffer = new byte[8 * 1024]; //自己定義拷貝檔案路徑 targetFile = new File(getCacheDir(context), fileName); if (targetFile.exists()) { targetFile.delete(); } OutputStream outputStream = new FileOutputStream(targetFile); while ((read = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return targetFile; }