Android Uri转File方法,适配android 10以上版本及android 10以下版本
博主在这里就不再做过多的阐述了,直接上代码,复制即用
public static File uriToFileApiQ(Uri uri, Context context) { File file = null; if (uri == null) return file; //android10以上转换 if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) { file = new File(uri.getPath()); } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) { //把文件复制到沙盒目录 ContentResolver contentResolver = context.getContentResolver(); String displayName = System.currentTimeMillis() + Math.round((Math.random() + 1) * 1000) + "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri)); try { InputStream is = contentResolver.openInputStream(uri); File cache = new File(context.getCacheDir().getAbsolutePath(), displayName); FileOutputStream fos = new FileOutputStream(cache); FileUtils.copy(is, fos); file = cache; fos.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } return file; }