如何将URI转换为Android 10的文件

9
如何在Android 10及以上版本中从URI获取文件对象或将URI转换为文件对象。
 final File file = new File(Environment.getExternalStorageDirectory(), "read.me");
 Uri uri = Uri.fromFile(file);

2
问题是:你为什么想要那个?你可以直接使用URI。 - blackapps
2
一些较旧的库无法识别URI,它们只接受文件对象,例如Retrofit、一些图像编辑器等。 - Mohammad irshad sheikh
我想将URI转换为文件并获取输入流。 - Akash kumar
@Akashkumar,您可以使用答案代码将URI转换为文件,然后使用 new FileInputStream(file); 进行输入流转换。 - Mohammad irshad sheikh
1个回答

34

在 Android 10 中,您无法将直接文件转换为 URI。相反,您可以将文件复制到文件目录中,以获取文件对象。

File f = getFile(getApplicationContext(), uri);
下面的方法为您提供URI文件对象,并且您在文件目录中也有该文件的副本。
    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;
}

如需更多详细信息,请参阅此处


1
抱歉,您在此博客中查找的页面不存在。 - K Pradeep Kumar Reddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接