Convert file: Uri to File in Android
use
InputStream inputStream = getContentResolver().openInputStream(uri);
directly and copy the file. Also see:
https://developer.android.com/guide/topics/providers/document-provider.html
Android + Kotlin
Add dependency for Kotlin Android extensions:
implementation 'androidx.core:core-ktx:{latestVersion}'
Get file from uri:
uri.toFile()
Android + Java
Just move to top ;)
What you want is...
new File(uri.getPath());
... and not...
new File(uri.toString());
Notes
- For an
android.net.Uri
object which is nameduri
and created exactly as in the question,uri.toString()
returns aString
in the format"file:///mnt/sdcard/myPicture.jpg"
, whereasuri.getPath()
returns aString
in the format"/mnt/sdcard/myPicture.jpg"
. - I understand that there are nuances to file storage in Android. My intention in this answer is to answer exactly what the questioner asked and not to get into the nuances.
After searching for a long time this is what worked for me:
File file = new File(getPath(uri));
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}