What's the easiest way to convert from a file:
android.net.Uri
to a File
in Android?
Tried the following but it doesn't work:
final File file = new File(Environment.getExternalStorageDirectory(), "read.me"); Uri uri = Uri.fromFile(file); File auxFile = new File(uri.toString()); assertEquals(file.getAbsolutePath(), auxFile.getAbsolutePath());
A URI is a uniform resource identifier while a URL is a uniform resource locator.
Uri uri = data. getData(); File file = new File(uri. getPath());//create path from uri final String[] split = file. getPath().
From what I know you can find the path of a file in the internal storage with java simply by using: String path = context. getFilesDir(). getAbsolutePath(); File file = new File(path + "/filename");
This don't work for image returned by: Intent photoPickerIntent = new Intent (Intent.ACTION_PICK); That case there is a need to convert Uri to real path by getRealPathFromURI () function. So the conclusion is that it depends on what type of Uri you want to convert to File. Show activity on this post.
Uri.fromFile (file).toString () only returns something like file///storage/emulated/0/* which is a simple absolute path of a file on the sdcard but with file// prefix (scheme) You can also get content uri using MediaStore database of Android TEST (what returns Uri.fromFile and what returns MediaScannerConnection ):
If your Android app wants to access other app created files, you should get the file from its ContentProvider with a content URI. The ContentProvider URI is not a real android file path URI ( file:///storage/41B7-12F1/DCIM/Camera/IMG_20180211_095139.jpg ), it is a content provider style URI ( content://media/external/images/media/1302716 ).
For this case, especially on Android, the way going for bytes is usually faster. With this, I solved it by setting up a class FileHelper which is given the responsibility to deal with reading/writing bytes from/to file through stream and a class UriHelper which is given the responsibility to figure out path of Uri and permission.
What you want is...
new File(uri.getPath());
... and not...
new File(uri.toString());
Note: uri.toString()
returns a String in the format: "file:///mnt/sdcard/myPicture.jpg"
, whereas uri.getPath()
returns a String in the format: "/mnt/sdcard/myPicture.jpg"
.
use
InputStream inputStream = getContentResolver().openInputStream(uri);
directly and copy the file. Also see:
https://developer.android.com/guide/topics/providers/document-provider.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With