sv_jan5
sv_jan5

Reputation: 1573

Making local copy of file using Google Drive API

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

Upvotes: 4

Views: 776

Answers (1)

Prima
Prima

Reputation: 271

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

Upvotes: 5

Related Questions