如何将 URI 转换为文件 Android 10 [英] how to convert URI to File Android 10

查看:50
本文介绍了如何将 URI 转换为文件 Android 10的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 URI 获取文件对象或在 android 10 及以上版本中将 URI 转换为文件对象.

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

推荐答案

您无法在 android 10 中将直接文件转换为 URI 而不是这样,您可以将该文件的副本复制到您的文件目录中,这将帮助您获得文件对象.

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

以下方法为您提供 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;
}

更多细节参考这里

这篇关于如何将 URI 转换为文件 Android 10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆