如何获取Google Drive文档的文件名和真实路径?

13

我正在使用以下代码获取文件管理器中文件的文件名和路径。但是,它不会返回Google Drive文件的路径。有什么办法可以获取实际路径吗?

我的代码 -

public String getFilePath() {
    if (uri.getScheme().equalsIgnoreCase("file")) {
        return uri.getLastPathSegment();
    }

    cursorLoader.setUri(uri);
    cursorLoader.setProjection(projections);
    Cursor cursor = cursorLoader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);
    cursor.moveToFirst();
    String realPath = cursor.getString(column_index);
    cursor.close();

    if (realPath == null || realPath.isEmpty()) {
        return null;
    }

return null;
}

1
不考虑细节,我的怀疑是它们实际上不是设备文件系统上的文字“文件”,而是指向某些信息共享计划的引用,可能用于获取内容。你有任何确凿证据表明它们真的是本地文件吗? - Chris Stratton
同意。任何Uri都没有必要有一个“实际路径”。您正在使用的代码片段最多只能与由MediaStore索引的文件一起使用。像Google Drive这样的应用程序可以通过ACTION_GET_CONTENTACTION_PICK,存储访问框架等方式提供文件内容。但是,这些文件不必在您可以独立访问它们的任何地方,例如将它们放在内部存储中。 - CommonsWare
它确实有一个内容URI - content://com.google.android.apps.docs.files/exposed_content/GzbCGuP7Bbpim%2FVz6FkjsA%3D%3D%0A%3BIaCw8dNKdKh2%2FIRHBzfQih86IT2FRnSTdSN6MS2d1L2UKC%2FuQyTlxUCOb%2Fu%2F0%2BlC%0A 这不意味着它位于设备上某个地方吗? - Suchi
1
这并不意味着它一定位于设备上的某个位置。它可能是一个您无法访问的文件(例如 Drive 应用程序的内部存储)。ContentProvider 可能会在流式传输时解密加密文件,并将其返回给客户端。ContentProvider 可能会从互联网上进行流式传输等等。从来没有要求 Uri 映射到文件,这就是为什么您的 MediaStore hack 在所有 Android 版本上都不可靠的原因。使用存储访问框架,Android 4.4+ 上将有更少的 Uri 值映射到文件。 - CommonsWare
那么获取Google Drive文件并存储路径是死路一条了吗?有什么解决方法吗?我这里也遇到了同样的问题 :) - Dennis Anderson
2个回答

10

您必须使用URI。通过URI,您可以使用getContentResolver.query(theUriThatYouHave, null, null, null, null)。现在您有了一个光标,可以检查列名等。

对于Google驱动器,有一个列名为_display_name。这将给出文件名。

现在您想要访问文件?您可以通过getContentResolver().openInputStream(theUriThatYouHave)打开流到URI。


5
你能否提供一个完整的例子来演示如何准确地从该路径获取文件? - Anand Savjani

6

按照以下步骤非常容易地从Google Drive URI获取文件名和真实路径:

  1. Add file provider path in Android manifest file.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.demo.filemangerdemo">
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.STORAGE" />
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name="com.demo.filemangerdemo.activity.MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <provider
                android:name="android.support.v4.content.FileProvider"
                android:authorities="${applicationId}.provider"
                android:exported="false"
                android:grantUriPermissions="true">
                <meta-data
                    android:name="android.support.FILE_PROVIDER_PATHS"
                    android:resource="@xml/provider_paths"/>
            </provider>
        </application>
    </manifest>
    
  2. Create xml folder under res and add provider_paths.xml.

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <cache-path
            name="my_cache"
            path="." />
        <cache-path
            name="cache"
            path="." />
        <external-cache-path
            name="external_cache"
            path="." />
        <files-path
            name="files"
            path="." />
    </paths>
    
  3. Utils class for access data from Google Drive.

    public class Utils {
        private static Uri contentUri = null;
    
        @SuppressLint("NewApi")
        public static String getPath(final Context context, final Uri uri) {
            // check here to KITKAT or new version
            final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
            // DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri))
              {
                // MediaProvider
                 if (isMediaDocument(uri)) {
                     if (isGoogleDriveUri(uri)) {
                    return getDriveFilePath(uri, context);
                }
    
    
              }
          }
    
  4. isGoogleDriveUri method

    private static boolean isGoogleDriveUri(Uri uri) {
        return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
    }
    
  5. getDriveFilePath method

    private static String getDriveFilePath(Uri uri, Context context) {
        Uri returnUri = uri;
        Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
        /*
         * Get the column indexes of the data in the Cursor,
         *     * move to the first row in the Cursor, get the data,
         *     * and display it.
         * */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
    
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));
        File file = new File(context.getCacheDir(), name);
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();
    
            //int bufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);
    
            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            Log.e("File Size", "Size " + file.length());
            inputStream.close();
            outputStream.close();
            Log.e("File Path", "Path " + file.getPath());
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }
            return file.getPath();
        }     
    }
    
  6. Getting file path in onActivityResult

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            if ((data != null) && (data.getData() != null)) {
                Uri selectedFile = data.getData();
                if (selectedFile.getLastPathSegment() != null) {
                    //Here you will get File Path
                    String strPath = FileUtils.getPath(this, selectedFile);  
                }
            }
        }
    }
    

以上代码运行良好。我们可以使用文件提供程序和上述步骤轻松地访问谷歌驱动器中的文件路径。 - Satyawan Hajare
你测试过这个代码在你的Google Drive的Google表格上吗?代码出现了异常。如果你有任何解决方案,请帮忙一下。先谢谢了。 - Shailesh

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