2

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();
                  }
             }

 });
Mo H.
  • 1,788
  • 1
  • 18
  • 28
Gaj
  • 150
  • 2
  • 15

3 Answers3

2

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

Gaj
  • 150
  • 2
  • 15
  • Imagine if you have a file with 500MB... When you do "fileInputStream.read(new byte[fileInputStream.available()]);", it reads only the "last byte" or it reads the entire file content? – Christian Mar 26 '15 at 15:14
  • Still I haven't played around with it. But for this line `fileInputStream.read(new byte[fileInputStream.available()]);` I think it reads the entire file contents and converts into bytes for writing in the end. For more info, checkout this [link](https://developers.google.com/drive/android/files) . – Gaj Mar 26 '15 at 17:34
  • ok... sounds like you're not appending to the end of the file... you're "rewriting" the entire... if we have a 2GB file, I think it could not be done this way... – Christian Mar 26 '15 at 18:19
  • @ChristianB.Almeida actually you're not rewriting the entire file. You're reading it all, sendind the "pointer" to the end of the file. Notice how the `FileInputStream` is never closed. When the `FileOutputStream` is created, the pointer will be where the `FileInputStream` left it. At least I suppose that is what is happening. – Gustavo Maciel Jun 21 '15 at 22:09
  • @Gaj what happen if file is just created and there is no data – H Raval Sep 09 '16 at 10:48
0

The reason is that commit's default resolution strategy is to overwrite existing files. Check the API docs and see if there is a way to append changes.

Mo H.
  • 1,788
  • 1
  • 18
  • 28
0

For anyone facing this problem in 2017 : Google has some methods to append data Here's a link!

Though copying the method from google didn't worked entirely for me , so here is the class which would append data : ( Please note this is a modified version of this code link )

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.preference.PreferenceManager;
import android.util.Log;

import com.google.android.gms.common.api.Result;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveApi.DriveIdResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveId;

/**
* An activity to illustrate how to edit contents of a Drive file.
*/
public class EditContentsActivity extends BaseDemoActivity {

private static final String TAG = "EditContentsActivity";

@Override
public void onConnected(Bundle connectionHint) {
    super.onConnected(connectionHint);

    final ResultCallback<DriveIdResult> idCallback = new ResultCallback<DriveIdResult>() {
        @Override
        public void onResult(DriveIdResult result) {
            if (!result.getStatus().isSuccess()) {
                showMessage("Cannot find DriveId. Are you authorized to view this file?");
                return;
            }
            DriveId driveId = result.getDriveId();
            DriveFile file = driveId.asDriveFile();
            new EditContentsAsyncTask(EditContentsActivity.this).execute(file);
        }
    };
    SharedPreferences sp= PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
    Drive.DriveApi.fetchDriveId(getGoogleApiClient(), EXISTING_FILE_ID)
            .setResultCallback(idCallback);
}

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

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

    @Override
    protected Boolean doInBackgroundConnected(DriveFile... args) {
        DriveFile file = args[0];
        SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(EditContentsActivity.this);
        System.out.println("0"+sp.getString("drive_id","1"));
        DriveContentsResult driveContentsResult=file.open(getGoogleApiClient(), DriveFile.MODE_READ_WRITE, null).await();
                System.out.println("1");
        if (!driveContentsResult.getStatus().isSuccess()) {
            return false;
        }
        DriveContents driveContents = driveContentsResult.getDriveContents();
                try {
                    System.out.println("2");
                    ParcelFileDescriptor parcelFileDescriptor = driveContents.getParcelFileDescriptor();
                    FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor
                            .getFileDescriptor());
                    // Read to the end of the file.
                    fileInputStream.read(new byte[fileInputStream.available()]);
                    System.out.println("3");
                    // Append to the file.
                    FileOutputStream fileOutputStream = new FileOutputStream(parcelFileDescriptor
                            .getFileDescriptor());
                    Writer writer = new OutputStreamWriter(fileOutputStream);
                    writer.write("hello world");
                    writer.close();
                    System.out.println("4");
                    driveContents.commit(getGoogleApiClient(), null).await();
                    return true;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return false;
        };








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

Existing_File_id is the resource id. Here is one link if you need resource id a link

Salman Saleh
  • 173
  • 2
  • 9