【问题标题】:File Chooser for get a document on google drive用于在谷歌驱动器上获取文档的文件选择器
【发布时间】:2018-03-17 06:32:29
【问题描述】:

我在使用文件选择器从谷歌驱动器中提取文档时遇到问题,但是当我选择它并为我带来 URI 时,我可以获得名称,但是当我创建文件时为空。

  1. 获取数据列:

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };
    
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
                DatabaseUtils.dumpCursor(cursor);
    
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
    

    }

2.获取路径的代码:

else if ("content".equalsIgnoreCase(uri.getScheme())) {
        if (isGooglePhotosUri(uri) || isGoogleDriveUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null); }

3.检查文件大小:

(new File(PathUtil.getPath( getActivity(), uri)).length() == 0){
   //alert
 }

【问题讨论】:

  • 请提供minimal reproducible example 并详细解释“我可以获取名称,但创建文件时为空”的含义。
  • 谢谢,问题已编辑。

标签: java android


【解决方案1】:

请参阅此文档: https://developer.android.com/guide/topics/providers/document-provider.html

尤其是这部分:

private String readTextFromUri(Uri uri) throws IOException {
InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(
        inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
    stringBuilder.append(line);
}
fileInputStream.close();
parcelFileDescriptor.close();
return stringBuilder.toString();
}

希望对你有帮助

【讨论】:

    【解决方案2】:

    您的问题中的任何代码都不正确。例如,不必有可用于查询任意Uri_data 列。

    Uri 不是文件。您无法获得一个文件系统路径。

    您没有显示您正在使用的“文件选择器”是什么。如果是ACTION_GET_CONTENTACTION_OPEN_DOCUMENT,请理解它们都不是“文件选择器”。您从那些返回的Uri 可以与DocumentFile.fromSingleUri() 一起使用。 DocumentFile 对象具有您可以使用的 getName()length() 方法。 length() 将返回内容的大小(以字节为单位)。 getName() 将返回用户应该识别的“显示名称”(但可能不是传统文件名)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 2017-06-11
      • 2017-11-27
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多