2

为了上传和下载文本文件,我一直在尝试将 google drive api 与我的代码集成。我已成功上传文件,但在下载时,输入流显示为空。

这是我尝试上传的方式:

IntentSender intentSender = Drive.DriveApi
                    .newOpenFileActivityBuilder()
                    .setMimeType(new String[] { "text/plain" })
                    .build(mGoogleApiClient);
            try {
                startIntentSenderForResult(intentSender,
                        REQUEST_CODE_OPENER, null, 0, 0, 0);
            } catch (SendIntentException e) {
                Log.w(TAG, "Unable to send intent", e);
            }

然后在 onActivityResult 中,这就是我正在做的事情:

DriveId driveId = (DriveId) data
                .getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
        showMessage(driveId.toString());

        DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, driveId);
        Log.v(TAG, file.toString());

        file.openContents(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).setResultCallback(contentsOpenedCallback);
        new ReadContentsAsyncTask(MainMusicActivity.this).execute(file);

我的 AsyncTask 类看起来像这样

public class ReadContentsAsyncTask extends
        ApiClientAsyncTask<DriveFile, Void, Boolean> {

    public ReadContentsAsyncTask(Context context) {
        super(context);
    }

    @Override
    protected Boolean doInBackgroundConnected(DriveFile... args) {
        String contents = null;
        DriveFile file = args[0];
        ContentsResult contentsResult =
                file.openContents(getGoogleApiClient(), DriveFile.MODE_READ_ONLY, null).await();
        if (!contentsResult.getStatus().isSuccess()) {
            Log.v(TAG,  "RETURNINNG!!!");
            return null;
        }
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(contentsResult.getContents().getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            contents = builder.toString();
            Log.v(TAG,  contents); // its empty
        } catch (IOException e) {
            Log.e(TAG, "IOException while reading from the stream", e);
        }

        Log.v(TAG,  contents);
        file.discardContents(getGoogleApiClient(), contentsResult.getContents()).await();
        return true;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (!result) {
            showMessage("Error while editing contents");
            return;
        }
        showMessage("Successfully edited contents");
    }
}

我无法弄清楚为什么我无法读取文件内容。

一个令人困惑的情况是,当我从网络在驱动器中创建一个文本文件时,此代码运行良好。

任何帮助将不胜感激。谢谢

4

0 回答 0