android uri 解析获取文件真实路径(兼容7.0+)
程序员文章站
2024-02-13 23:17:34
...
主要是兼容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;
}