如何获取Google驱动器文档的文件名和实际路径?

问题描述 投票:12回答:2

我使用以下代码来获取文件管理器中的文件名和文件路径。但是,它不会返回Google云端硬盘文件的路径。知道如何获得实际路径吗?

我的代码 -

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;
}
android google-drive-sdk
2个回答
10
投票

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

对于Google云端硬盘,列名为_display_name。这将为您提供文件名。

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


0
投票

通过以下步骤轻松获取Google云端硬盘URI中的文件名和实际路径:

  1. 在Android清单文件中添加文件提供程序路径。 <?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. 在res下创建xml文件夹并添加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类用于访问Google云端硬盘的数据。 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. 是GoogleDriveUri方法 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方法 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. 获取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); } } } }
© www.soinside.com 2019 - 2024. All rights reserved.