使用Google Drive Android API将数据附加到文件

sv_*_*an5 1 android google-api google-drive-android-api

我正尝试使用https://developers.google.com/drive/android/files#making_modifications中提供的程序将数据附加到Google云端硬盘上的现有文件中

虽然控制正常但没有变化反映在文件中.

    public void addHistoryEntry(final String location) {
            final DriveFile file = Drive.DriveApi.getFile(getClient(), historyFileId);
            file.open(getClient(), DriveFile.MODE_READ_WRITE, null)
                    .setResultCallback(new ResultCallback<DriveContentsResult>() {
                            @Override
                            public void onResult(DriveContentsResult driveContentsResult) {
                                    if (!driveContentsResult.getStatus().isSuccess()) {
                                            L.c("Problem in Writing to file");
                                            return;
                                    }
                                    DriveContents contents = driveContentsResult.getDriveContents();
                                    try {
                                            ParcelFileDescriptor parcelFileDescriptor = contents.getParcelFileDescriptor();
                                            FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
                                            // Read to the end of the file.
                                            fileInputStream.read(new byte[fileInputStream.available()]);

                                            // Append to the file.
                                            FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
                                                    .getFileDescriptor());
                                            Writer writer = new OutputStreamWriter(fileOutputStream);
                                            writer.write(location+"\n");
                                    } catch (IOException e) {
                                            e.printStackTrace();
                                    }

                                    contents.commit(getClient(), null).setResultCallback(new ResultCallback<Status>() {
                                            @Override
                                            public void onResult(Status status) {
                                                    if(status.isSuccess()) L.c("Write to file successful");
                                                    else L.c("Write to file failed");
                                            }
                                    });
                            }
                    });
    }
Run Code Online (Sandbox Code Playgroud)

请帮我调试代码.

小智 5

在提交内容之前,你能尝试刷新你的OutputStream,即writer.flush()吗?

另外,考虑使用FileOutputStream#getChannel而不是读取InputStream中的所有现有字节,因为FileChannel具有快速搜索到文件末尾的功能,即fileChannel.position(fileChannel.size())