4

I want to make local copy(external storage) of a '.ppt' file present on Google Drive using Google Drive android Api.

I am reading one byte and writing it to my local file. But when I am trying to open it shows that file is corrupt. Please help me to resolve my problem.

final DriveFile file = Drive.DriveApi.getFile(getClient(), fileid);
final Metadata[] metadata = new Metadata[1];

file.getMetadata(getClient())
.setResultCallback(new ResultCallback<DriveResource.MetadataResult>() {
    @Override
    public void onResult(DriveResource.MetadataResult metadataResult) {
        metadata[0] = metadataResult.getMetadata();
        L.b(EditorWindow.this, metadata[0].getMimeType(), 0);
    }
});

file.open(getClient(), DriveFile.MODE_READ_ONLY, null)
.setResultCallback(new ResultCallback<DriveApi.DriveContentsResult>() {
    @Override
    public void onResult(DriveApi.DriveContentsResult result) {
        if (!result.getStatus().isSuccess()) {
            L.c("Error in creating new file");
            return;
        }
        DriveContents contents = result.getDriveContents();
        String filename = metadata[0].getTitle();
        File localFile = new File(Environment.getExternalStorageDirectory(), filename);
        OutputStream out = null;
        InputStream in = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            in = contents.getInputStream();
            int b;
            while ( (b = in.read()) > 0) {
                out.write(b);
            }
            in.close();
            out.close();
        } catch (Exception e) {L.c("Error in writing to SD card");}
        contents.discard(getClient());
    }
});
sv_jan5
  • 1,543
  • 16
  • 42
  • I've tried this with txt files and it works as expected did you try with other file types? Is the ppt in question here a Google Slides Document or a Microsoft Power Point doc? – Arthur Thompson Jun 29 '15 at 18:37
  • @kroikie 'ppt' referes to Microsoft powerpoint ppt – sv_jan5 Jun 30 '15 at 05:11

1 Answers1

5

Can you try changing your while condition to ( (b = in.read()) >= 0)? Note that 0 is a valid byte to be read from an InputStream. http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()

Prima
  • 271
  • 1
  • 4