首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将URI转换为文件Android 10

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

Stack Overflow用户
提问于 2020-12-25 18:21:41
回答 1查看 2.5K关注 0票数 3

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

代码语言:javascript
运行
复制
 final File file = new File(Environment.getExternalStorageDirectory(), "read.me");
 Uri uri = Uri.fromFile(file);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-25 18:21:41

在Android10中,您不能将直接文件转换为URI,相反,您可以将该文件的副本复制到您的文件目录中,这将帮助您获取文件对象。

代码语言:javascript
运行
复制
File f = getFile(getApplicationContext(), uri);

下面的方法为您提供了URI的文件对象,并且在您的文件目录中也有该文件的副本。

代码语言:javascript
运行
复制
    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;
}

有关更多详细信息,请参阅here

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65447194

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档