【问题标题】:how to convert URI to File Android 10如何将 URI 转换为文件 Android 10
【发布时间】:2021-04-03 10:18:17
【问题描述】:

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

 final File file = new File(Environment.getExternalStorageDirectory(), "read.me");
 Uri uri = Uri.fromFile(file);

【问题讨论】:

  • 问题是:你为什么想要那个?可以直接使用uri。
  • 一些较旧的库无法识别 URI,它们只需要文件对象,如改造、一些图像编辑器等。

标签: android file storage uri


【解决方案1】:

您不能在 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;
}

更多详情请参考here

【讨论】:

  • 提供的参考链接无效“抱歉,您在此博客中查找的页面不存在。”
猜你喜欢
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多