Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert URI to File Android 10

how to get file object from URI OR convert URI to file object in android 10 and above versions.

 final File file = new File(Environment.getExternalStorageDirectory(), "read.me");
 Uri uri = Uri.fromFile(file);
like image 510
Mohammad irshad sheikh Avatar asked Jan 25 '23 13:01

Mohammad irshad sheikh


1 Answers

You cannot convert the direct file to URI in android 10 instead of this you can make a copy of the file into your file directory which will help you to get a file object.

File f = getFile(getApplicationContext(), uri);

The below method provide you file object of URI and also you have a copy of the file in your file directory.

    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;
}

for more detail refer here

like image 138
Mohammad irshad sheikh Avatar answered Jan 29 '23 23:01

Mohammad irshad sheikh