Search code examples
javaandroidandroid-activitygoogle-drive-android-api

Couldn't append the text onto a Google Drive File


I am trying to append text to a text file on the Google Drive. But when I write, it whole file is overwritten. Why can't I just add the text in the end of the file?

  DriveFile file = Drive.DriveApi.getFile(mGoogleApiClient, id);
  file.open(mGoogleApiClient, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
        @Override
          public void onResult(DriveApi.DriveContentsResult driveContentsResult) {
                  msg.Log("ContentsOpenedCallBack");

                  if (!driveContentsResult.getStatus().isSuccess()) {
                     Log.i("Tag", "On Connected Error");
                     return;
                  }

                  final DriveContents driveContents = driveContentsResult.getDriveContents();

                  try {
                     msg.Log("onWrite");
                     OutputStream outputStream = driveContents.getOutputStream();
                     Writer writer = new OutputStreamWriter(outputStream);
                     writer.append(et.getText().toString());
                     writer.close();
                     driveContents.commit(mGoogleApiClient, null);

                  } catch (IOException e) {
                     e.printStackTrace();
                  }
             }

 });

Solution

  • Finally I've found the answer to append the text on the drive document.

     DriveContents contents = driveContentsResult.getDriveContents();
    
     try {
    
          String input = et.getText().toString();
    
          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("\n"+input);
    
          writer.close();
          driveContentsResult.getDriveContents().commit(mGoogleApiClient, null);
    
     } catch (IOException e) {
                        e.printStackTrace();
         }
    

    SO