how to convert URI to File Android 10 and above
how to convert URI to File Android 10 and above
how to get file object from URI OR convert URI to file object in android 10 and above versions.
some libraries are required File Objects for a process like a retrofit, some image editor e.t.c.
to convert URI to file object or anything similar we have a way which is to support all android old versions and upcoming versions.
Step 1:
you have to create a new file inside FilesDir which is nonreadable to other Apps with the same name as our file and extension.
Step 2:
you have to copy the content of the URI to create a file by using InputStream.
After these two steps it will return your File object
File f = getFile(getApplicationContext(), uri);
For example
This method provide you file object and it supports all available
andoid versions and upcomming version too
public static File getFile(Context context, Uri uri) throws IOException {
File destinationFilename = new File(context.getFilesDir().getPath() + File.separatorChar + queryName(context, uri));
try (InputStream ins = context.getContentResolver().openInputStream(uri)) {
createFileFromStream(ins, destinationFilename);
} catch (Exception ex) {
Log.e("Save File", ex.getMessage());
ex.printStackTrace();
}
return destinationFilename;
}
public static void createFileFromStream(InputStream ins, File destination) {
try (OutputStream os = new FileOutputStream(destination)) {
byte[] buffer = new byte[4096];
int length;
while ((length = ins.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.flush();
} catch (Exception ex) {
Log.e("Save File", ex.getMessage());
ex.printStackTrace();
}
}
private static String queryName(Context context, Uri uri) {
Cursor returnCursor =
context.getContentResolver().query(uri, null, null, null, null);
assert returnCursor != null;
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
String name = returnCursor.getString(nameIndex);
returnCursor.close();
return name;
}
Thank you
Comments
Post a Comment